Setting Status Code
Use thestatus_code parameter in your path operation decorator:
The
status_code parameter:- Sets the HTTP status code in the response
- Documents it in the OpenAPI schema
- Validates that it’s a valid HTTP status code
Using the status Module
Instead of memorizing numeric codes, use FastAPI’sstatus module:
Common Status Codes
Success Codes (2xx)
Redirection Codes (3xx)
Client Error Codes (4xx)
Server Error Codes (5xx)
Status Code Reference
2xx Success
1
200 OK
Default success response (GET, PUT, PATCH)
2
201 Created
Resource successfully created (POST)
3
202 Accepted
Request accepted but processing not complete
4
204 No Content
Success with no response body (DELETE)
3xx Redirection
- 301 Moved Permanently: Resource permanently moved
- 302 Found: Temporary redirect (legacy)
- 307 Temporary Redirect: Temporary redirect (preserves method)
- 308 Permanent Redirect: Permanent redirect (preserves method)
4xx Client Errors
- 400 Bad Request: Invalid request data
- 401 Unauthorized: Authentication required
- 403 Forbidden: Authenticated but not authorized
- 404 Not Found: Resource doesn’t exist
- 422 Unprocessable Entity: Validation error
- 429 Too Many Requests: Rate limit exceeded
5xx Server Errors
- 500 Internal Server Error: Unexpected server error
- 502 Bad Gateway: Invalid upstream response
- 503 Service Unavailable: Service temporarily down
- 504 Gateway Timeout: Upstream timeout
Dynamic Status Codes
Change status codes dynamically usingResponse:
When using
Response to set status codes dynamically, the code set in the decorator becomes the default shown in docs.Status Codes with HTTPException
Raise exceptions with specific status codes:Best Practices
Status Code Guidelines
Testing Status Codes
Related Topics
- Response Model - Define response schemas
- Extra Models - Work with multiple models
- Request Body - Handle request data