Guides

Error handling and status codes

When implementing an integration it is important to include error handling. This guide gives a few ideas.

Important HTTP response codes:

2xx (Success): Request was successful:

  • 200 OK: General success.
  • 201 Created: Resource created successfully.

4xx (Client Errors): Issue with the request:

  • 400 Bad Request: Invalid input or malformed request: Check your parameters and function call.
  • 401 Unauthorized: Authentication required or failed: Check your tenant and credentials.
  • 403 Forbidden: Lacking permission to access: Check your permissions for the API user.
  • 404 Not Found: Resource not found.
  • 429 Too Many Requests: Rate-limiting hit: Reduce the frequency of API calls

5xx (Server Errors): Server-side issues:

  • 500 Internal Server Error: General server issue.
  • 502 Bad Gateway: API service is down or unresponsive.
  • 503 Service Unavailable: Temporary downtime.

Implement Retry Logic

For temporary errors (i.e. 429 Too Many Requests, 503 Service Unavailable), implement retries with exponential backoff.

Example:

import time

for attempt in range(5):  # Retry 5 times  
    try:  
        response = requests.get("<https://api.operations1.app/tenants/<tenant>/users/<userId>">, timeout=5)  
        response.raise_for_status()  
        break  # Exit loop on success  
    except requests.exceptions.RequestException as e:  
        if attempt < 4:  # Retry only on first 4 attempts  
            time.sleep(2 ** attempt)  # Exponential backoff  
        else:  
            print(f"Failed after 5 attempts: {e}")

Log errors

Log all errors for debugging and monitoring purposes.

Example:

import logging

logging.basicConfig(level=logging.ERROR, filename="api_errors.log")

try:
    response = requests.get("https://api.operations1.app/tenants/<tenant>/users/<userId>")
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    logging.error(f"API error: {e}")

Test error scenarios

Simulate and test common API error scenarios:

  • Invalid inputs
  • Authentication failure
  • Server unavailability