AltSportsData

Error Handling

Understanding error responses and codes

Error Handling

The AltSportsData API uses standard HTTP response codes and provides detailed error messages to help you troubleshoot issues.

HTTP Status Codes

CodeStatusDescription
200OKRequest succeeded
201CreatedResource created successfully
400Bad RequestInvalid request parameters
401UnauthorizedMissing or invalid API key
403ForbiddenAPI key doesn't have required permissions
404Not FoundResource not found
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer error
503Service UnavailableTemporary service disruption

Error Response Format

All error responses follow a consistent structure:

{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": {
      "field": "Additional context about the error"
    }
  }
}

Common Error Codes

Authentication Errors

{
  "error": {
    "code": "INVALID_API_KEY",
    "message": "The provided API key is invalid or has been revoked"
  }
}

Validation Errors

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "details": {
      "limit": "Must be between 1 and 100",
      "offset": "Must be a non-negative integer"
    }
  }
}

Not Found Errors

{
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "League with ID 'league_123' not found"
  }
}

Rate Limit Errors

{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Please retry after 1678886400",
    "retry_after": 1678886400
  }
}

Error Handling Best Practices

import requests

def handle_api_request(url, headers):
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.json()
    
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            print("Authentication failed. Check your API key.")
        elif e.response.status_code == 404:
            print("Resource not found.")
        elif e.response.status_code == 429:
            print("Rate limit exceeded. Please wait.")
        else:
            print(f"HTTP error: {e.response.status_code}")
            print(e.response.json())
    
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
async function handleApiRequest(url, headers) {
  try {
    const response = await fetch(url, { headers });
    
    if (!response.ok) {
      const error = await response.json();
      
      switch (response.status) {
        case 401:
          console.error('Authentication failed. Check your API key.');
          break;
        case 404:
          console.error('Resource not found.');
          break;
        case 429:
          console.error('Rate limit exceeded. Please wait.');
          break;
        default:
          console.error(`HTTP error: ${response.status}`, error);
      }
      throw new Error(error.error.message);
    }
    
    return await response.json();
  } catch (error) {
    console.error('Request failed:', error);
    throw error;
  }
}
require 'net/http'
require 'json'

def handle_api_request(uri, headers)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(uri)
  headers.each { |k, v| request[k] = v }

  response = http.request(request)

  case response.code.to_i
  when 200
    JSON.parse(response.body)
  when 401
    puts 'Authentication failed. Check your API key.'
  when 404
    puts 'Resource not found.'
  when 429
    puts 'Rate limit exceeded. Please wait.'
  else
    error = JSON.parse(response.body)
    puts "HTTP error: #{response.code}"
    puts error
  end
end

Best Practices

  1. Always check status codes before processing responses
  2. Log error details for debugging and monitoring
  3. Implement retry logic for transient errors (500, 503)
  4. Validate input before making API requests
  5. Handle rate limits gracefully with exponential backoff
  6. Never expose API keys in error messages or logs

On this page