Last modified: Nov 12, 2024 By Alexander Williams

Python HTTP Status Codes: A Guide to Request Response Handling

HTTP status codes are essential indicators of the outcome of web requests. When working with the Python requests library, understanding these codes is crucial for building robust applications.

Common HTTP Status Code Categories

Status codes are grouped into five categories, each serving a specific purpose in HTTP communications. Let's explore how to handle them using Python Requests.

1. 2XX Success Codes

These codes indicate successful requests. The most common is 200 OK, but there are others you should know about when working with API responses.


import requests

response = requests.get('https://api.github.com')
if response.status_code == 200:
    print('Success!')
    print(response.json())

2. 3XX Redirection Codes

Redirection codes indicate that further action is needed. The requests library handles these automatically, but you can customize this behavior as discussed in our guide on handling redirects.


response = requests.get('http://example.com', allow_redirects=False)
if response.status_code == 301:
    print(f'Redirected to: {response.headers["Location"]}')

3. 4XX Client Error Codes

These indicate client-side errors. The most common are 404 (Not Found) and 401 (Unauthorized). Here's how to handle them:


try:
    response = requests.get('https://api.example.com/resource')
    response.raise_for_status()
except requests.exceptions.HTTPError as err:
    if err.response.status_code == 404:
        print('Resource not found')
    elif err.response.status_code == 401:
        print('Authentication required')

4. 5XX Server Error Codes

Server errors require special handling. You might want to implement retries when encountering these errors:


from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

session = requests.Session()
retry = Retry(total=3, backoff_factor=1)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)

Best Practices for Status Code Handling

Always check status codes in your requests. Here's a comprehensive example combining various handling techniques:


def make_api_request(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        
        if response.status_code == 200:
            return response.json()
            
    except requests.exceptions.HTTPError as http_err:
        print(f'HTTP error occurred: {http_err}')
    except requests.exceptions.ConnectionError as conn_err:
        print(f'Error connecting: {conn_err}')
    except requests.exceptions.Timeout as timeout_err:
        print(f'Timeout error: {timeout_err}')
    except requests.exceptions.RequestException as err:
        print(f'Error occurred: {err}')
    return None

Custom Status Code Handling

When working with APIs, you might need to handle specific status codes differently. Here's an example using a custom handler:


def handle_response(response):
    status_handlers = {
        200: lambda r: {'success': True, 'data': r.json()},
        401: lambda r: {'success': False, 'message': 'Authentication required'},
        404: lambda r: {'success': False, 'message': 'Resource not found'},
        500: lambda r: {'success': False, 'message': 'Server error'}
    }
    
    handler = status_handlers.get(response.status_code, 
                                lambda r: {'success': False, 'message': f'Unexpected status: {r.status_code}'})
    return handler(response)

Conclusion

Understanding HTTP status codes is crucial for building reliable applications with Python Requests. Use proper error handling and consider implementing retries for robust API interactions.

For more advanced topics, check our guides on authentication and session management.