Skip to main content

Overview

HTTP headers provide metadata about responses. FastAPI makes it easy to set custom headers for caching, security, content negotiation, and application-specific metadata.

Setting Headers with Response Classes

Return a response object with custom headers:
Custom headers typically start with X- by convention, though this is no longer strictly required by HTTP specifications.

Using Response Parameter

Inject a Response parameter to set headers while returning data normally:
This approach lets you leverage FastAPI’s automatic response serialization while still setting custom headers.

Common Use Cases

Cache Control

Set caching headers to control browser and proxy caching:

Security Headers

Add security-related headers:
While setting security headers at the endpoint level works, it’s usually better to set them globally using middleware for consistency.

CORS Headers

Set Cross-Origin Resource Sharing (CORS) headers:
For production applications, use FastAPI’s built-in CORS middleware instead of manually setting headers.

Content Type and Encoding

Specify content type and character encoding:

Rate Limiting Headers

Include rate limit information:

Multiple Headers

Set multiple headers at once:

Dynamic Headers

Generate headers dynamically based on request or business logic:

Headers in Different Response Types

HTMLResponse with Headers

FileResponse with Headers

StreamingResponse with Headers

Modifying Existing Headers

Update or remove headers:

Response Header Middleware

For global headers, use middleware:
Use middleware to add headers that should be present on all responses, such as security headers or API versioning information.

Best Practices

  1. Use standard headers: Prefer standard HTTP headers over custom ones when possible
  2. Consistent naming: Use consistent naming conventions for custom headers (e.g., X- prefix)
  3. Security headers: Set security headers globally via middleware
  4. Cache appropriately: Use cache headers to optimize performance
  5. Document custom headers: Document any custom headers in your API documentation
  6. Avoid sensitive data: Don’t expose sensitive information in headers
  7. Use Response parameter: Prefer the Response parameter injection for cleaner code
  8. CORS via middleware: Handle CORS with middleware, not manual headers