API

Documentation

Version 1.0

Error Handling

The AutoTechJobs API uses conventional HTTP response codes to indicate the success or failure of an API request. This page explains how to interpret and handle the various error responses you might encounter.

Error Response Format

All error responses from the API follow a consistent format, making it easier to handle errors in your application. Error responses include an HTTP status code in the response header and a JSON body with additional details.

Example Error Response

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": {
    "code": "invalid_request",
    "message": "The job title field is required",
    "documentation_url": "https://api.autotechjobs.co.uk/docs/api/errors#invalid_request",
    "param": "title",
    "details": [
      {
        "field": "title",
        "message": "This field is required"
      }
    ]
  }
}

Error Object Properties

PropertyTypeDescription
codestringA machine-readable error code that identifies the error
messagestringA human-readable message providing more details about the error
documentation_urlstringA URL pointing to more information about the error
paramstringThe parameter that caused the error (if applicable)
detailsarrayAdditional details about the error, often for validation errors

HTTP Status Codes

The AutoTechJobs API uses the following HTTP status codes to indicate the success or failure of an API request:

Status CodeDescription
200 - OKThe request was successful
201 - CreatedThe request was successful and a resource was created
204 - No ContentThe request was successful but there is no content to return
400 - Bad RequestThe request was invalid or cannot be otherwise served
401 - UnauthorizedAuthentication is required and has failed or has not been provided
403 - ForbiddenThe request is understood, but it has been refused or access is not allowed
404 - Not FoundThe requested resource does not exist
409 - ConflictThe request conflicts with the current state of the server
422 - Unprocessable EntityThe request was well-formed but was unable to be followed due to semantic errors
429 - Too Many RequestsThe request was rejected due to rate limiting
500 - Internal Server ErrorSomething went wrong on our end
503 - Service UnavailableThe server is currently unable to handle the request due to temporary overloading or maintenance

Common Error Codes

The following are common error codes that you may encounter when using the AutoTechJobs API:

Error CodeHTTP StatusDescription
invalid_request400The request was invalid or malformed
invalid_param400One or more parameters in the request were invalid
missing_param400A required parameter was missing from the request
authentication_required401Authentication is required for this endpoint
invalid_api_key401The API key provided is invalid
expired_api_key401The API key provided has expired
permission_denied403You do not have permission to access this resource
resource_not_found404The requested resource does not exist
resource_conflict409The request conflicts with the current state of the resource
validation_error422The request data failed validation
rate_limit_exceeded429You have exceeded the rate limit for this endpoint
internal_error500An internal error occurred on the server
service_unavailable503The service is temporarily unavailable

Handling Errors

Here are some best practices for handling errors in your application:

  • Check HTTP status codes: Always check the HTTP status code of the response to determine if the request was successful.
  • Parse error messages: Extract and display the error message from the response to provide meaningful feedback to your users.
  • Implement retry logic: For certain errors (like rate limiting or temporary server issues), implement retry logic with exponential backoff.
  • Log errors: Log errors for debugging and monitoring purposes.
  • Handle validation errors: For validation errors, display the specific field errors to help users correct their input.

Code Examples

Handling Errors in JavaScript

async function createJob(jobData) {
  try {
    const response = await fetch('https://api.autotechjobs.co.uk/v1/jobs', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(jobData)
    });
    
    const data = await response.json();
    
    if (!response.ok) {
      // Handle API errors
      const error = data.error;
      
      switch (error.code) {
        case 'validation_error':
          // Handle validation errors
          const fieldErrors = error.details.reduce((acc, detail) => {
            acc[detail.field] = detail.message;
            return acc;
          }, {});
          
          console.error('Validation errors:', fieldErrors);
          // Update your UI to show validation errors
          break;
          
        case 'rate_limit_exceeded':
          // Handle rate limiting
          const resetTime = new Date(parseInt(response.headers.get('X-RateLimit-Reset')) * 1000);
          console.error(`Rate limit exceeded. Try again after ${resetTime.toLocaleTimeString()}`);
          // Maybe schedule a retry after the reset time
          break;
          
        default:
          // Handle other errors
          console.error(`API Error: ${error.code} - ${error.message}`);
          // Show a generic error message to the user
      }
      
      return { success: false, error };
    }
    
    return { success: true, data: data.data };
  } catch (error) {
    // Handle network errors
    console.error('Network error:', error);
    return { 
      success: false, 
      error: { 
        code: 'network_error', 
        message: 'A network error occurred. Please check your connection and try again.' 
      } 
    };
  }
}

Handling Errors in Python

import requests
import time

def create_job(job_data, api_key):
    try:
        response = requests.post(
            'https://api.autotechjobs.co.uk/v1/jobs',
            json=job_data,
            headers={
                'Authorization': f'Bearer {api_key}',
                'Content-Type': 'application/json'
            }
        )
        
        # Parse the response
        data = response.json()
        
        # Check if the request was successful
        if response.status_code >= 400:
            error = data.get('error', {})
            error_code = error.get('code')
            error_message = error.get('message')
            
            if error_code == 'validation_error':
                # Handle validation errors
                field_errors = {detail['field']: detail['message'] for detail in error.get('details', [])}
                print(f'Validation errors: {field_errors}')
                # Update your UI to show validation errors
                
            elif error_code == 'rate_limit_exceeded':
                # Handle rate limiting
                reset_time = int(response.headers.get('X-RateLimit-Reset', 0))
                wait_time = max(0, reset_time - int(time.time()))
                print(f'Rate limit exceeded. Try again after {wait_time} seconds')
                # Maybe sleep and retry
                
            else:
                # Handle other errors
                print(f'API Error: {error_code} - {error_message}')
                # Show a generic error message to the user
                
            return {'success': False, 'error': error}
        
        return {'success': True, 'data': data.get('data')}
        
    except requests.exceptions.RequestException as e:
        # Handle network errors
        print(f'Network error: {str(e)}')
        return {
            'success': False,
            'error': {
                'code': 'network_error',
                'message': 'A network error occurred. Please check your connection and try again.'
            }
        }