Return Proper HTTP Status Codes Table in Python
Mock HTTP status code table with proper numeric and textual representations, including formatted status lines and a filtered table view.
Python code
40 lines# Mock HTTP status code table with proper numeric and textual representations
codes = {
200: "OK",
201: "Created",
204: "No Content",
301: "Moved Permanently",
302: "Found",
304: "Not Modified",
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
500: "Internal Server Error",
502: "Bad Gateway",
503: "Service Unavailable",
}
def get_status(code):
"""Return proper HTTP status line for a code."""
return f"HTTP/1.1 {code} {codes[code]}"
def status_table(prefix="2"):
"""Return formatted table of matching codes."""
filtered = {k: v for k, v in codes.items() if str(k).startswith(prefix)}
if not filtered:
return "No matching status codes found."
lines = [f"{code:<6} {desc}" for code, desc in sorted(filtered.items())]
return "\n".join(lines)
if __name__ == "__main__":
print(get_status(200))
print(get_status(404))
print("\n2xx codes:")
print(status_table("2"))
print("\n4xx codes:")
print(status_table("4"))
Output
HTTP/1.1 200 OK
HTTP/1.1 404 Not Found
2xx codes:
200 OK
201 Created
204 No Content
4xx codes:
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
How it works
The codes dictionary maps integer HTTP status codes to their canonical reason phrases. The get_status function uses an f-string to build a proper status line, which is the exact format a server would send in its HTTP response header. The status_table function uses a dictionary comprehension to filter codes by prefix, then formats them with aligned columns using the :<6 format specifier. Sorting the filtered items ensures consistent, readable output. This approach keeps the mock table easy to extend and reuse across tests or documentation.
Common mistakes
- Using string keys for the status codes, which breaks integer lookups
- Forgetting to sort the filtered codes before printing
- Assuming all codes have the same phrase length without using alignment
Variations
- Use `functools.lru_cache` to cache `get_status` for repeated calls
- Return a tuple instead of f-string for easier serialization
Real-world use cases
- Mocking HTTP responses in unit tests to verify client error handling.
- Generating a status code reference sheet for API documentation.
- Building a diagnostic CLI tool that prints status codes for debugging server responses.
Sponsored
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.