Overview
While you typically set a default status code in the path operation decorator, sometimes you need to dynamically change the status code based on your business logic. FastAPI provides flexible ways to handle this.Using Response Parameter
The most common way to dynamically change status codes is to inject aResponse parameter:
The decorator’s
status_code=200 sets the default status code documented in OpenAPI. You can override it at runtime using the response parameter.Common Status Code Patterns
Create or Update (Upsert)
Return different status codes for creation vs. update:Conditional Success
Return different success codes based on the operation result:Empty Responses
Return 204 No Content for successful operations without data:Using JSONResponse
Return aJSONResponse with a specific status code:
Partial Success Scenarios
Handle partial success with appropriate status codes:Validation-Based Status Codes
Change status codes based on validation logic:Async Operations
Handle async operations with appropriate status codes:Resource State Changes
Reflect resource state in status codes:Status Code Constants
FastAPI’sstatus module provides readable constants:
Using these constants makes your code more readable and helps prevent typos in status code numbers.
Best Practices
- Set sensible defaults: Use the decorator’s
status_codeparameter for the most common case - Use status constants: Import and use
status.HTTP_*constants for better readability - Document all codes: Use the
responsesparameter to document all possible status codes - Be consistent: Use the same status codes for similar operations across your API
- Follow HTTP semantics: Use status codes according to their intended meaning
- Prefer Response parameter: Use
Responseparameter injection for cleaner code - Return appropriate bodies: Match response bodies to status codes (e.g., no body for 204)
- Consider HTTPException: For error cases,
HTTPExceptionis often cleaner than changing status codes
Common HTTP Status Codes Guide
- 200 OK: Standard success response
- 201 Created: Resource successfully created
- 202 Accepted: Request accepted for processing (async)
- 204 No Content: Success with no response body
- 400 Bad Request: Invalid request data
- 401 Unauthorized: Authentication required
- 403 Forbidden: Authenticated but not authorized
- 404 Not Found: Resource doesn’t exist
- 409 Conflict: Request conflicts with current state
- 422 Unprocessable Entity: Validation error
- 500 Internal Server Error: Server-side error
- 503 Service Unavailable: Temporary service unavailability