Skip to main content

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 the responses 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 a JSONResponse object with a specific status code:

Using Response Parameter

Inject a Response 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 the status module:
Using status.HTTP_* constants makes your code more readable and less error-prone than using numeric codes.

Documenting Multiple Responses

Provide comprehensive documentation for all possible responses:

Response Models with Different Status Codes

Define different response models for different status codes:
When using the responses parameter, make sure your actual endpoint code can return all documented status codes. The documentation won’t automatically validate this.

Combining with HTTPException

Use HTTPException for error responses while documenting them:

Best Practices

  1. Document all status codes: Include all possible status codes your endpoint might return in the responses parameter
  2. Use meaningful descriptions: Provide clear descriptions for each status code
  3. Include examples: Add example responses to help API consumers understand the structure
  4. Be consistent: Use the same error response format across your API
  5. Use status constants: Prefer status.HTTP_* over numeric codes for better readability