Skip to main content

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 a Response 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:
When returning 204 No Content, you should not return any response body. Return None or an empty Response object.

Using JSONResponse

Return a JSONResponse 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:
For validation errors, consider using HTTPException with a 422 status code instead of manually changing the response status.

Async Operations

Handle async operations with appropriate status codes:

Resource State Changes

Reflect resource state in status codes:

Status Code Constants

FastAPI’s status module provides readable constants:
Using these constants makes your code more readable and helps prevent typos in status code numbers.

Best Practices

  1. Set sensible defaults: Use the decorator’s status_code parameter for the most common case
  2. Use status constants: Import and use status.HTTP_* constants for better readability
  3. Document all codes: Use the responses parameter to document all possible status codes
  4. Be consistent: Use the same status codes for similar operations across your API
  5. Follow HTTP semantics: Use status codes according to their intended meaning
  6. Prefer Response parameter: Use Response parameter injection for cleaner code
  7. Return appropriate bodies: Match response bodies to status codes (e.g., no body for 204)
  8. Consider HTTPException: For error cases, HTTPException is 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