Overview
Your API endpoints often need to return different HTTP status codes based on different scenarios. FastAPI makes it easy to handle multiple status codes and document them in your OpenAPI schema.The Responses Parameter
Use theresponses parameter to document additional status codes that your endpoint might return:
The
responses parameter is primarily for OpenAPI documentation. It tells consumers of your API what responses to expect.Returning Different Status Codes
There are several ways to return different status codes in FastAPI:Using JSONResponse
Return aJSONResponse object with a specific status code:
Using Response Parameter
Inject aResponse parameter and modify its status code:
This approach is cleaner when you want to return the same data structure but with different status codes.
Common Status Codes
FastAPI provides common status codes through thestatus module:
Documenting Multiple Responses
Provide comprehensive documentation for all possible responses:Response Models with Different Status Codes
Define different response models for different status codes:Combining with HTTPException
UseHTTPException for error responses while documenting them:
Best Practices
- Document all status codes: Include all possible status codes your endpoint might return in the
responsesparameter - Use meaningful descriptions: Provide clear descriptions for each status code
- Include examples: Add example responses to help API consumers understand the structure
- Be consistent: Use the same error response format across your API
- Use status constants: Prefer
status.HTTP_*over numeric codes for better readability