Status codes
An HTTP status code is the three-digit number that classifies a response: 2xx succeeded, 3xx redirect, 4xx client error, 5xx server error. Clients, proxies, and caches branch on it before they read the body.
Detailed Explanation
200 OK is a successful GET or an unopinionated success. 201 Created is a successful POST that made a resource; send Location. 204 No Content is success with an empty body, typical for DELETE. 304 Not Modified is a cache hit.
400 Bad Request is a malformed or invalid body. 401 Unauthorized means "unauthenticated" — the name is historical. 403 Forbidden means authenticated but not allowed. 404 Not Found is unknown URL or hidden resource (some APIs use 404 instead of 403 to avoid leaking ids). 409 Conflict is a version clash. 422 Unprocessable Entity is a popular choice for validation errors on a well-formed JSON body. 429 Too Many Requests is rate limiting; send Retry-After.
500 is an unhandled crash. 502/503/504 are gateway and availability problems. Do not catch every exception and return 400; 500 is the honest answer when your code is wrong, and it is what alerts page on.
In Flask, return {"error": "not_found"}, 404. In FastAPI, raise HTTPException(status_code=404). Django uses HttpResponseNotFound or DRF's Response(..., status=404). Pick one mapping and keep it.
Do not invent 200 with {"status": 500}. Do not use 418 in production humour. Do not return 301 for a POST unless you mean the client to change method to GET on the follow-up (use 308/307 when you must preserve the method).
Document the codes your API actually emits. A client that only checks if resp.ok treats 201 and 204 the same, which is usually fine, and treats 301 as success after a follow, which may not be.
Code Examples
def create_order(exists: bool) -> tuple[int, dict]:
if exists:
return 409, {"error": "duplicate"}
return 201, {"id": "12"}
def require_user(token: str | None) -> tuple[int, dict]:
if token is None:
return 401, {"error": "unauthenticated"}
if token != "admin":
return 403, {"error": "forbidden"}
return 200, {"user": "ada"}
print(create_order(False)[0], require_user(None)[0]) # 201 401Common Gotchas
401 vs 403
missing token is 401. Known user, wrong role is 403. Mixing them breaks client login flows.
301 on an API POST
many clients convert the retry to GET and drop the body.
Always 200 for JSON-RPC style errors
HTTP middleware cannot help you. Use real codes on REST endpoints.
`requests` `resp.ok` is 2xx
301 is not ok until you follow; 404 is never ok.