Understand and handle API errors effectively
The Connect2Print API uses standard HTTP status codes and structured error responses to communicate problems. This guide helps you understand and handle errors correctly.
All API errors are returned in the following standard format:
{
"success": false,
"error": {
"code": "validation_error",
"message": "Invalid input data",
"details": {
"email": ["Email format is invalid"],
"quantity": ["Must be at least 1"]
}
}
}
Response Fields:
success - Always false for errorserror - Object containing error detailserror.code - Machine-readable error codeerror.message - Human-readable error messageerror.details - (Optional) Additional error informationThe API uses standard HTTP status codes:
200 OK - Request succeeded201 Created - Resource was created204 No Content - Successful deletion400 Bad Request - Invalid request or validation error401 Unauthorized - Missing or invalid authentication403 Forbidden - Insufficient permissions404 Not Found - Resource not found409 Conflict - Conflict with existing resource422 Unprocessable Entity - Validation error429 Too Many Requests - Rate limit exceeded500 Internal Server Error - Server error502 Bad Gateway - Gateway error503 Service Unavailable - Service temporarily unavailableThe API uses the following error codes:
unauthorized - Invalid or missing API keyinsufficient_permissions - API key lacks required scopesexpired_token - API key has expiredrevoked_token - API key has been revokedvalidation_error - Input data is invalidmissing_field - Required field is missinginvalid_format - Field has wrong formatinvalid_value - Field value is invalidnot_found - Resource not foundduplicate_resource - Resource already existsinvalid_state - Operation not allowed in current stateresource_locked - Resource is lockedrate_limit_exceeded - Too many requestsserver_error - Internal server errorservice_unavailable - Service temporarily unavailableHTTP/1.1 400 Bad Request { "success": false, "error": { "code": "validation_error", "message": "Validation failed", "details": { "email": ["Email format is invalid"], "quantity": ["Must be between 1 and 1000"] } } }
HTTP/1.1 401 Unauthorized { "success": false, "error": { "code": "unauthorized", "message": "Invalid API key" } }
HTTP/1.1 403 Forbidden { "success": false, "error": { "code": "insufficient_permissions", "message": "API key lacks required scope: orders:write" } }
HTTP/1.1 404 Not Found { "success": false, "error": { "code": "not_found", "message": "Order not found" } }
HTTP/1.1 429 Too Many Requests Retry-After: 60 { "success": false, "error": { "code": "rate_limit_exceeded", "message": "Rate limit exceeded. Try again in 60 seconds." } }
Follow these best practices when handling API errors:
Use the HTTP status code to determine error type before parsing response body.
Use the error.code field to determine the specific error and handle appropriately.
Don't show raw API error messages to end users. Translate to user-friendly messages.
Log the full error response, request details, and context for debugging.
For validation errors, show which fields are invalid and why.
For 5xx errors and 429, implement retry with exponential backoff.
Track error rates over time to identify issues early.
Handle timeout, connection errors, and other network issues gracefully.
Examples of error handling in different languages:
try { $response = makeApiRequest($url, $apiKey); if (!$response['success']) { $errorCode = $response['error']['code']; $errorMessage = $response['error']['message']; switch ($errorCode) { case 'unauthorized': handleUnauthorized(); break; case 'validation_error': handleValidationError($response['error']['details']); break; case 'rate_limit_exceeded': handleRateLimit(); break; default: handleGenericError($errorMessage); } } } catch (Exception $e) { error_log("API request failed: " . $e->getMessage()); }
try { const response = await makeApiRequest(url, apiKey); if (!response.success) { const { code, message, details } = response.error; switch (code) { case 'unauthorized': handleUnauthorized(); break; case 'validation_error': handleValidationError(details); break; case 'rate_limit_exceeded': await handleRateLimit(); break; default: handleGenericError(message); } } } catch (error) { console.error('API request failed:', error); }
try: response = make_api_request(url, api_key) if not response['success']: error = response['error'] code = error['code'] message = error['message'] if code == 'unauthorized': handle_unauthorized() elif code == 'validation_error': handle_validation_error(error.get('details')) elif code == 'rate_limit_exceeded': handle_rate_limit() else: handle_generic_error(message) except Exception as e: print(f'API request failed: {e}')
Tips for debugging API issues:
Each response includes an X-Request-Id header. Save this for support requests.
Review your API request logs in the admin panel to see request/response details.
Isolate the problem by testing the same request in Postman or cURL.
Ensure all required headers are set correctly (Authorization, Content-Type, etc.).
Ensure request body is valid JSON without syntax errors.
If experiencing widespread errors, check the API status page for known issues.
Explore related topics: