HTTP Codes Module
Overview
The http_codes module provides a comprehensive HTTP status code and response management system for FastAPI. It offers a type-safe interface for sending HTTP responses with proper content types, status codes, and headers.
Location: backend/src/libs/http_codes/
Key Components:
HttpCodes - Main response builder class
http_constants.py - HTTP status codes, MIME types, and DataTypes enum
- Global instance
HCI - Ready-to-use HttpCodes singleton
Architecture
See http_codes_architecture.puml for visual representation.
Core Classes
HttpCodes
A final class that standardizes HTTP response creation across all status codes (1xx-5xx).
Purpose: Provides consistent, type-safe HTTP responses with proper FastAPI response types based on content type.
Key Features:
- 80+ predefined HTTP status code methods
- Automatic response type selection (JSONResponse, HTMLResponse, FileResponse, etc.)
- MIME type validation and normalization
- Support for DataTypes enum, string keys, and raw MIME strings
- Content type detection and processing
Constructor:
Key Methods:
| Method | Description | Return Type |
send_message_on_status() | Generic response builder | Response |
_package_correctly() | Select appropriate FastAPI response class | Response subclass |
_check_data_type() | Validate and normalize content type | str (MIME type) |
_check_header() | Validate header mapping | Dict[str, str] |
_process_data_content() | Process content based on type | Any |
DataTypes Enum
An enumeration of common HTTP content (MIME) types with convenient access methods.
Purpose: Provides type-safe content type selection with string-based lookup.
Features:
- 100+ MIME types covering common file formats
- Alphabetically sorted members
- Case-insensitive key lookup via
from_key()
- Support for hyphenated and underscored names
Usage:
DataTypes.JSON.value
DataTypes.from_key('json')
DataTypes.from_key('HTML')
DataTypes.from_key('pdf')
Categories:
| Category | Examples |
| Archive | _7Z, GZIP, ZIP, TAR |
| Audio | MP3, WAV, OGG, AAC |
| Data | JSON, XML, CSV, YAML |
| Document | PDF, DOC, DOCX, ODT |
| Font | TTF, WOFF, WOFF2, EOT |
| Image | PNG, JPEG, GIF, WEBP, SVG |
| Text | PLAIN, HTML, CSS, JAVASCRIPT |
| Video | MP4, WEBM, AVI, MOV |
| Special | OCTET_STREAM, FORM_DATA, FORM_URLENCODED |
HTTP Status Codes
The module supports all standard HTTP status codes organized by category:
1xx - Informational
http_codes.continue_(content)
http_codes.switching_protocols(content)
http_codes.processing(content)
http_codes.early_hints(content)
2xx - Success
http_codes.ok(content)
http_codes.created(content)
http_codes.accepted(content)
http_codes.no_content()
http_codes.reset_content()
http_codes.partial_content(content)
3xx - Redirection
http_codes.moved_permanently(url)
http_codes.found(url)
http_codes.see_other(url)
http_codes.not_modified()
http_codes.temporary_redirect(url)
http_codes.permanent_redirect(url)
4xx - Client Errors
http_codes.bad_request(message)
http_codes.unauthorized(message)
http_codes.forbidden(message)
http_codes.not_found(message)
http_codes.method_not_allowed(message)
http_codes.not_acceptable(message)
http_codes.request_timeout(message)
http_codes.conflict(message)
http_codes.unprocessable_entity(message)
http_codes.too_many_requests(message)
5xx - Server Errors
http_codes.internal_server_error(message)
http_codes.not_implemented(message)
http_codes.bad_gateway(message)
http_codes.service_unavailable(message)
http_codes.gateway_timeout(message)
Configuration (http_constants.py)
AUTHORISED_STATUSES
List of all valid HTTP status codes:
AUTHORISED_STATUSES: List[int] = [
100, 101, 102, ...,
200, 201, 202, ...,
300, 301, 302, ...,
400, 401, 403, ...,
500, 501, 502, ...
]
MIME Type Groups
Constants grouping related MIME types:
FILE_MIME_TYPES: Set[str]
HTML_MIME_TYPES: Set[str]
JSON_MIME_TYPES: Set[str]
PLAIN_TEXT_MIME_TYPES: Set[str]
REDIRECT_MIME_TYPES: Set[str]
STREAMING_MIME_TYPES: Set[str]
UJSON_MIME_TYPES: Set[str]
ORJSON_MIME_TYPES: Set[str]
DEFAULT_MESSAGE_TYPE & DEFAULT_MESSAGE_CONTENT
Default values for responses:
DEFAULT_MESSAGE_TYPE: str = "application/json"
DEFAULT_MESSAGE_CONTENT: str = ""
Response Type Selection
The module automatically selects the appropriate FastAPI response class:
| Content Type | FastAPI Response Class | Use Case |
| File paths | FileResponse | Serving static files |
| HTML/XML/JS | HTMLResponse | Web pages, scripts |
| JSON | JSONResponse | API responses (default) |
| Plain text | PlainTextResponse | Text content |
| Redirect | RedirectResponse | URL redirects |
| Streaming | StreamingResponse | Large files, media |
| UJSON | UJSONResponse | Ultra-fast JSON |
| ORJSON | ORJSONResponse | Optimized JSON |
| Other | Response | Generic fallback |
Usage Examples
Example 1: Simple JSON Response
@app.get("/api/user")
def get_user():
data = {"id": 123, "name": "John Doe"}
return HCI.ok(
content=data,
content_type=HttpDataTypes.JSON
)
Example 2: Using DataTypes Enum
@app.get("/api/report")
def get_report():
return HCI.ok(
content={"report": "data"},
content_type=DataTypes.JSON
)
Example 3: Using String Keys
@app.post("/api/data")
def create_data():
return HCI.created(
content={"id": 456},
content_type="json"
)
Example 4: Error Responses
@app.get("/api/resource/{id}")
def get_resource(id: int):
resource = database.get(id)
if not resource:
return HCI.not_found(
content={"error": "Resource not found"},
content_type="json"
)
return HCI.ok(content=resource)
Example 5: File Download
@app.get("/download/report")
def download_report():
return HCI.ok(
content="/path/to/report.pdf",
content_type=DataTypes.PDF,
headers={"Content-Disposition": 'attachment; filename="report.pdf"'}
)
Example 6: HTML Response
@app.get("/page")
def get_page():
html_content = "<html><body><h1>Hello World</h1></body></html>"
return HCI.ok(
content=html_content,
content_type=DataTypes.HTML
)
Example 7: Redirect
@app.get("/old-path")
def redirect_old_path():
return HCI.moved_permanently(
content="https://example.com/new-path",
content_type="redirect"
)
Example 8: Custom Status with Headers
@app.post("/api/webhook")
def webhook_handler():
return HCI.accepted(
content={"status": "processing"},
content_type="json",
headers={"X-Request-ID": "abc123"}
)
Example 9: Generic Status Code
@app.get("/custom")
def custom_response():
return HCI.send_message_on_status(
status=418,
content={"message": "I'm a teapot"},
content_type=DataTypes.JSON
)
Content Type Resolution
The module supports multiple ways to specify content types:
HCI.ok(content=data, content_type=DataTypes.JSON)
HCI.ok(content=data, content_type="json")
HCI.ok(content=data, content_type="JSON")
HCI.ok(content=data, content_type="application/json")
HCI.ok(content=data)
Error Handling
Type Validation:
try:
HCI.ok(content=data, content_type=12345)
except TypeError as e:
print(f"Invalid data type: {e}")
try:
HCI.send_message_on_status(status=999, content=data)
except ValueError as e:
print(f"Invalid status code: {e}")
Header Validation:
try:
HCI.ok(content=data, headers="invalid")
except TypeError as e:
print(f"Invalid header format: {e}")
Best Practices
- Use the global
HCI instance - Already instantiated and ready to use
- Prefer enum members -
DataTypes.JSON is more type-safe than "json"
- Use specific status methods -
HCI.not_found() is clearer than HCI.send_message_on_status(404)
- Include error details - Always provide meaningful error messages
- Set proper headers - Use ServerHeaders module for standardized headers
- Handle file paths carefully - Ensure files exist before returning FileResponse
- Use streaming for large content - Prevents memory issues
- Validate content type matches content - Don't send JSON with HTML content type
Global Instance
The module exports a global HCI instance:
return HCI.ok({"status": "success"})
Dependencies
Related Modules