Skip to main content

HTTP Response Codes

A comprehensive Python library providing HTTP status code constants and exceptions.

PyPI version Python Support License: MIT

Overview

http-response-codes is a Python library that provides a comprehensive set of HTTP status codes as exception classes. Each status code is represented by a class that inherits from HTTPStatus, containing the numeric code, message, and description.

The module covers all standard HTTP status codes in the following categories:

  • 1xx: Informational responses (100-103)
  • 2xx: Success responses (200-208, 226)
  • 3xx: Redirection responses (300-308)
  • 4xx: Client error responses (400-431, 451)
  • 5xx: Server error responses (500-511)

Installation

pip install http-response-codes

Or using uv:

uv add http-response-codes

Features

  • Complete coverage of HTTP status codes
  • Each status code is a proper Python exception class
  • Class-level comparisons without instantiation required
  • Rich comparison operators (==, <, <=, >, >=)
  • Compare with both integers and strings
  • Type conversion support (int(), str())
  • Hashable - use as dictionary keys or in sets
  • Type hints included
  • Predefined groups of related status codes
  • Category predicate helpers (is_success, is_client_error, is_server_error, etc.)
  • Detailed descriptions for each status code
  • Zero dependencies

Usage

Basic Usage

from response_codes import HTTP_404_NOT_FOUND

# Raise as an exception
raise HTTP_404_NOT_FOUND()

# Access status code properties (no instantiation needed!)
print(HTTP_404_NOT_FOUND.status_code)  # 404
print(HTTP_404_NOT_FOUND.message)      # "Not Found"
print(HTTP_404_NOT_FOUND.description)  # Detailed description

# Compare directly with integers (class-level magic!)
assert HTTP_404_NOT_FOUND == 404
assert HTTP_404_NOT_FOUND == "Not Found"

Using Status Code Groups

from response_codes import (
    HTTP_INFORMATIONAL,
    HTTP_SUCCESS,
    HTTP_REDIRECTION,
    HTTP_CLIENT_ERRORS,
    HTTP_SERVER_ERRORS,
)

# Check if a status code is in a group
status_code = 404
if status_code in HTTP_CLIENT_ERRORS:
    print("This is a client error!")

Status Category Helpers

Category predicate helpers: is_informational, is_success, is_redirection, is_client_error, is_server_error. They accept an int, a status class, or a status instance; unsupported types raise TypeError.

Practical example:

from response_codes import HTTP_202_ACCEPTED, HTTP_429_TOO_MANY_REQUESTS, is_success, is_client_error
is_success(202)  # True
is_success(HTTP_202_ACCEPTED)  # True
is_success(HTTP_202_ACCEPTED())  # True
is_success(302)  # False
is_client_error(HTTP_429_TOO_MANY_REQUESTS)  # True
is_client_error(404)  # True
is_client_error(3.14)  # TypeError: value must be int or HTTPStatus
is_client_error(None)  # TypeError: value must be int or HTTPStatus

Advanced Comparison Features

The library uses a metaclass to enable powerful comparison operations directly on the status code classes (no instantiation required):

Compare with Integers or Strings

from response_codes import HTTP_404_NOT_FOUND, HTTP_200_OK

# Integer comparison
if HTTP_404_NOT_FOUND == 404:
    print("It's a 404!")

# String comparison
if HTTP_200_OK == "OK":
    print("Request succeeded")

# Rich comparisons for range checking
if 400 <= HTTP_404_NOT_FOUND < 500:
    print("Client error")

if HTTP_500_INTERNAL_SERVER_ERROR >= 500:
    print("Server error")

Type Conversions

from response_codes import HTTP_404_NOT_FOUND

# Convert to integer
status_code = int(HTTP_404_NOT_FOUND)  # 404

# Convert to string
status_msg = str(HTTP_404_NOT_FOUND)   # "Not Found"

Use in Collections

Status codes are hashable and can be used as dictionary keys or in sets:

from response_codes import (
    HTTP_200_OK,
    HTTP_404_NOT_FOUND,
    HTTP_500_INTERNAL_SERVER_ERROR,
)

# As dictionary keys
handlers = {
    HTTP_200_OK: handle_success,
    HTTP_404_NOT_FOUND: handle_not_found,
    HTTP_500_INTERNAL_SERVER_ERROR: handle_error,
}

# In sets
critical_errors = {
    HTTP_500_INTERNAL_SERVER_ERROR,
    HTTP_503_SERVICE_UNAVAILABLE,
}

Real-World Examples

Flask/FastAPI Response Handling

from flask import jsonify
from response_codes import (
    HTTP_200_OK,
    HTTP_404_NOT_FOUND,
    HTTP_400_BAD_REQUEST,
)

@app.route('/api/user/<int:user_id>')
def get_user(user_id):
    user = db.get_user(user_id)

    if not user:
        return (
            jsonify({"error": str(HTTP_404_NOT_FOUND)}),
            int(HTTP_404_NOT_FOUND)
        )

    return jsonify(user), int(HTTP_200_OK)

Exception Handling with Detailed Information

from response_codes import HTTP_404_NOT_FOUND, HTTPStatus

try:
    resource = fetch_resource(resource_id)
    if not resource:
        raise HTTP_404_NOT_FOUND()
except HTTP_404_NOT_FOUND as e:
    logger.error(f"{e.status_code} - {e.message}: {e.description}")
    return {"error": e.message}, e.status_code
except HTTPStatus as e:
    # Catch any HTTP status exception
    logger.error(f"HTTP Error {e.status_code}: {e.message}")
    return {"error": e.message}, e.status_code

Status Code Validation and Range Checking

from response_codes import HTTP_CLIENT_ERRORS

def handle_api_response(status_code):
    # Check if status code is in client error range
    if status_code in HTTP_CLIENT_ERRORS:
        retry_request()

    # Check status code ranges using comparisons
    if 200 <= status_code < 300:
        return "Success"
    elif 300 <= status_code < 400:
        return "Redirection"
    elif 400 <= status_code < 500:
        return "Client Error"
    elif 500 <= status_code < 600:
        return "Server Error"

Custom Error Groups

from response_codes import (
    create_status_group,
    HTTP_401_UNAUTHORIZED,
    HTTP_403_FORBIDDEN,
)

# Create custom groups for your application
AUTH_ERRORS = create_status_group(
    HTTP_401_UNAUTHORIZED,
    HTTP_403_FORBIDDEN,
)

def requires_auth(status_code):
    return status_code in AUTH_ERRORS

Development

This project uses modern Python tooling:

  • uv for dependency management
  • ruff for linting and formatting
  • mypy for type checking
  • pytest for testing
  • pre-commit for git hooks

Setup Development Environment

Clone the repository:

git clone https://github.com/seapagan/response-codes.git
cd response-codes

Install development dependencies:

uv sync

Install pre-commit hooks:

prek install

Running Tests

poe test # or simply run 'pytest'

Or in watch mode:

poe test:watch

Code Quality Checks

# Run all pre-commit checks
poe pre

# Run mypy type checking
poe mypy

# Run ruff linting
poe ruff

# Run ruff formatting
poe format

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate and adhere to the existing coding style.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Created and maintained by Grant Ramsay

Metadata

Release files for http-response-codes 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for http-response-codes 0.6.0
File Size Uploaded Provenance
http_response_codes-0.6.0.tar.gz 15.0 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for http-response-codes 0.6.0
File Interpreter ABI Platform
http_response_codes-0.6.0-py3-none-any.whl Python 3 none any Details

Total release size: 33.9 kB

Release files / http_response_codes-0.6.0.tar.gz

Download URL http_response_codes-0.6.0.tar.gz
Size 15.0 kB
Tags Source
SHA-256 checksum
How to use checksums
8136b5032810c044b8658cca7df458c714a1fa05b82df45f9951d8a677f6b5cc
BLAKE2b-256 checksum
How to use checksums
53ac518a30615f504b69a87384967f522684519e91bf75b477270e5da16750fd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / http_response_codes-0.6.0-py3-none-any.whl

Download URL http_response_codes-0.6.0-py3-none-any.whl
Size 18.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fce937530cd7251a58ff8b3be81401dcd245c1792c7f2dbb8b9aec6145ecebe8
BLAKE2b-256 checksum
How to use checksums
01f1a79842a3efb282d557b3b03cd8b8b96d440f5185c5075ffb004936ddcc74
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for http-response-codes 0.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page