HTTP Status Codes — Python source
Searchable reference of all HTTP status codes with meaning, category, and usage notes.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""HTTP Status Codes reference — pure, deterministic data + filter.
Language: Python 3.10+
CosmoDev polyglot showcase port of ``http-status-codes``,
ported from ``src/lib/httpStatus.ts``.
Display source — part of CosmoDev's polyglot tool pages.
No I/O, no third-party packages — standard library only. Behavior matches the
TypeScript lib: same inputs produce identical outputs.
"""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from enum import Enum
from typing import Optional
class StatusCategory(Enum):
"""The five broad families an HTTP status code can belong to.
Values are the canonical display strings used across HTTP tooling, so a
category can be resolved from free text via ``StatusCategory(value)``.
"""
INFORMATIONAL = "Informational"
SUCCESS = "Success"
REDIRECTION = "Redirection"
CLIENT_ERROR = "Client Error"
SERVER_ERROR = "Server Error"
@dataclass(frozen=True)
class StatusCode:
"""A single HTTP status code entry.
Frozen so instances are hashable and safe to share as immutable reference
data — the table is never mutated.
"""
code: int
reason: str
category: StatusCategory
description: str
# Standard + widely-implemented HTTP status codes across 1xx–5xx.
#
# A tuple (immutable) of frozen dataclass instances — the whole table is
# constant. Order is grouped by category, ascending within each group.
STATUS_CODES: tuple[StatusCode, ...] = (
# --- 1xx Informational ---
StatusCode(100, "Continue", StatusCategory.INFORMATIONAL, "The server has received the request headers and the client should proceed to send the request body."),
StatusCode(101, "Switching Protocols", StatusCategory.INFORMATIONAL, "The requester has asked the server to switch protocols and the server has agreed to do so."),
StatusCode(103, "Early Hints", StatusCategory.INFORMATIONAL, "Used to return some response headers before the final HTTP message so the browser can start preloading resources."),
# --- 2xx Success ---
StatusCode(200, "OK", StatusCategory.SUCCESS, "Standard response for a successful HTTP request."),
StatusCode(201, "Created", StatusCategory.SUCCESS, "The request succeeded and a new resource was created."),
StatusCode(202, "Accepted", StatusCategory.SUCCESS, "The request has been accepted for processing but is not yet complete."),
StatusCode(203, "Non-Authoritative Information", StatusCategory.SUCCESS, "The returned metadata originated from a local or third-party copy rather than the origin server."),
StatusCode(204, "No Content", StatusCategory.SUCCESS, "The server processed the request successfully but is not returning any content."),
StatusCode(205, "Reset Content", StatusCategory.SUCCESS, "The server asks the client to reset the document view that sent the request."),
StatusCode(206, "Partial Content", StatusCategory.SUCCESS, "The server is delivering only part of the resource because the client requested a byte range."),
StatusCode(207, "Multi-Status", StatusCategory.SUCCESS, "WebDAV: conveys information about multiple resources in a single XML response."),
StatusCode(208, "Already Reported", StatusCategory.SUCCESS, "WebDAV: the members of a DAV binding have already been enumerated in a previous reply."),
StatusCode(226, "IM Used", StatusCategory.SUCCESS, "The server fulfilled a GET request using an instance-manipulation applied to the current instance."),
# --- 3xx Redirection ---
StatusCode(300, "Multiple Choices", StatusCategory.REDIRECTION, "The request has more than one possible response; the user agent can choose among them."),
StatusCode(301, "Moved Permanently", StatusCategory.REDIRECTION, "This and all future requests should be directed to the given URL."),
StatusCode(302, "Found", StatusCategory.REDIRECTION, "The resource resides temporarily under a different URL; the method may be changed to GET."),
StatusCode(303, "See Other", StatusCategory.REDIRECTION, "The response to the request can be found under another URI using a GET request."),
StatusCode(304, "Not Modified", StatusCategory.REDIRECTION, "The resource has not been modified since the version specified by the request headers."),
StatusCode(305, "Use Proxy", StatusCategory.REDIRECTION, "The requested resource is available only through a proxy (deprecated)."),
StatusCode(306, "Switch Proxy", StatusCategory.REDIRECTION, "No longer used; originally meant subsequent requests should use a specified proxy."),
StatusCode(307, "Temporary Redirect", StatusCategory.REDIRECTION, "The request should be repeated with another URL; the request method must not change."),
StatusCode(308, "Permanent Redirect", StatusCategory.REDIRECTION, "This and all future requests should use another URL; the request method must not change."),
# --- 4xx Client Error ---
StatusCode(400, "Bad Request", StatusCategory.CLIENT_ERROR, "The server cannot process the request due to a client error such as malformed syntax."),
StatusCode(401, "Unauthorized", StatusCategory.CLIENT_ERROR, "Authentication is required and has either failed or not been provided."),
StatusCode(402, "Payment Required", StatusCategory.CLIENT_ERROR, "Reserved for future use; sometimes used for paywalled resources."),
StatusCode(403, "Forbidden", StatusCategory.CLIENT_ERROR, "The server understood the request but refuses to authorize it."),
StatusCode(404, "Not Found", StatusCategory.CLIENT_ERROR, "The requested resource could not be found on the server."),
StatusCode(405, "Method Not Allowed", StatusCategory.CLIENT_ERROR, "The request method is not supported for the requested resource."),
StatusCode(406, "Not Acceptable", StatusCategory.CLIENT_ERROR, "The requested resource can only generate content not acceptable per the Accept headers."),
StatusCode(407, "Proxy Authentication Required", StatusCategory.CLIENT_ERROR, "The client must first authenticate itself with the proxy."),
StatusCode(408, "Request Timeout", StatusCategory.CLIENT_ERROR, "The server timed out waiting for the client to send the request."),
StatusCode(409, "Conflict", StatusCategory.CLIENT_ERROR, "The request could not be processed because of a conflict with the current state of the resource."),
StatusCode(410, "Gone", StatusCategory.CLIENT_ERROR, "The resource is no longer available and will not be available again."),
StatusCode(411, "Length Required", StatusCategory.CLIENT_ERROR, "The request did not specify the length of its content, which is required by the resource."),
StatusCode(412, "Precondition Failed", StatusCategory.CLIENT_ERROR, "The server does not meet one of the preconditions given in the request headers."),
StatusCode(413, "Content Too Large", StatusCategory.CLIENT_ERROR, "The request payload is larger than the server is willing or able to process."),
StatusCode(414, "URI Too Long", StatusCategory.CLIENT_ERROR, "The URI provided was too long for the server to process."),
StatusCode(415, "Unsupported Media Type", StatusCategory.CLIENT_ERROR, "The request uses a media type the server does not support for the resource."),
StatusCode(416, "Range Not Satisfiable", StatusCategory.CLIENT_ERROR, "The portion of the resource requested in the Range header cannot be supplied by the server."),
StatusCode(417, "Expectation Failed", StatusCategory.CLIENT_ERROR, "The server cannot meet the requirements of the Expect request header field."),
StatusCode(418, "I'm a Teapot", StatusCategory.CLIENT_ERROR, "RFC 2324 joke status: the server refuses to brew coffee because it is, permanently, a teapot."),
StatusCode(421, "Misdirected Request", StatusCategory.CLIENT_ERROR, "The request was directed at a server that is not able to produce a response."),
StatusCode(422, "Unprocessable Content", StatusCategory.CLIENT_ERROR, "The server understands the content type and syntax but cannot process the contained instructions (WebDAV)."),
StatusCode(423, "Locked", StatusCategory.CLIENT_ERROR, "WebDAV: the source or destination resource of the method is locked."),
StatusCode(424, "Failed Dependency", StatusCategory.CLIENT_ERROR, "WebDAV: the method could not be performed because the requested action depended on another action that failed."),
StatusCode(425, "Too Early", StatusCategory.CLIENT_ERROR, "The server is unwilling to risk processing a request that might be a replay."),
StatusCode(428, "Precondition Required", StatusCategory.CLIENT_ERROR, "The origin server requires the request to be conditional."),
StatusCode(429, "Too Many Requests", StatusCategory.CLIENT_ERROR, "The user has sent too many requests in a given time (rate limiting)."),
StatusCode(431, "Request Header Fields Too Large", StatusCategory.CLIENT_ERROR, "The server is unwilling to process the request because its header fields are too large."),
StatusCode(451, "Unavailable For Legal Reasons", StatusCategory.CLIENT_ERROR, "The resource is unavailable due to legal demands such as government censorship or a takedown."),
# --- 5xx Server Error ---
StatusCode(500, "Internal Server Error", StatusCategory.SERVER_ERROR, "A generic error message: the server encountered an unexpected condition."),
StatusCode(501, "Not Implemented", StatusCategory.SERVER_ERROR, "The server does not support the functionality required to fulfill the request."),
StatusCode(502, "Bad Gateway", StatusCategory.SERVER_ERROR, "The server, acting as a gateway, received an invalid response from an upstream server."),
StatusCode(503, "Service Unavailable", StatusCategory.SERVER_ERROR, "The server is currently unavailable, typically because it is overloaded or down for maintenance."),
StatusCode(504, "Gateway Timeout", StatusCategory.SERVER_ERROR, "The server, acting as a gateway, timed out waiting for an upstream response."),
StatusCode(505, "HTTP Version Not Supported", StatusCategory.SERVER_ERROR, "The server does not support the HTTP protocol version used in the request."),
StatusCode(506, "Variant Also Negotiates", StatusCategory.SERVER_ERROR, "Transparent content negotiation for the request resulted in a circular reference."),
StatusCode(507, "Insufficient Storage", StatusCategory.SERVER_ERROR, "WebDAV: the server is unable to store the representation needed to complete the request."),
StatusCode(508, "Loop Detected", StatusCategory.SERVER_ERROR, "WebDAV: the server detected an infinite loop while processing the request."),
StatusCode(510, "Not Extended", StatusCategory.SERVER_ERROR, "Further extensions to the request are required for the server to fulfill it."),
StatusCode(511, "Network Authentication Required", StatusCategory.SERVER_ERROR, "The client must authenticate to gain network access, as with a captive portal."),
)
def _category_from_name(name: str) -> Optional[StatusCategory]:
"""Resolve a category by its display value, or None if unknown.
``StatusCategory(value)`` raises ValueError for an unrecognized string; we
translate that into None so callers can treat it as "matches nothing",
mirroring the TypeScript behavior.
"""
try:
return StatusCategory(name)
except ValueError:
return None
def filter_codes(
query: str,
codes: Sequence[StatusCode],
category: Optional[str] = None,
) -> list[StatusCode]:
"""Filter status codes by a free-text query and an optional category.
- ``query`` is matched case-insensitively against the numeric code, the
reason phrase, and the description. An empty/whitespace query returns
every code (within the chosen category, if one is supplied).
- ``category``, when provided and a known name, restricts the pool to that
category before the text match. A blank category means "no restriction";
an unknown name yields an empty list — matching the TypeScript semantics.
Note: ``str.lower`` coincides with JavaScript's ``toLowerCase`` for the
ASCII text in this table; ordering is preserved (original order is stable).
"""
cat_name = (category or "").strip()
# Step 1 — build the candidate pool by category.
if cat_name == "":
pool = list(codes)
else:
resolved = _category_from_name(cat_name)
if resolved is None:
# Unknown category: nothing can match, so short-circuit to empty.
return []
# Identity (``is``) is correct here: enum members are singletons.
pool = [c for c in codes if c.category is resolved]
# Step 2 — case-insensitive substring match across code/reason/description.
q = query.strip().lower()
if not q:
return pool
return [
c for c in pool
# The code is matched against its decimal string form, so "40" hits 404, 405, ...
if q in str(c.code)
or q in c.reason.lower()
or q in c.description.lower()
]
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →