Skip to main content
HTTP headers contain metadata about requests and responses. FastAPI makes it easy to read and validate headers using the Header() function.

Basic Header Parameter

Use Header() to declare header parameters:
Header() works like Query() and Cookie(), but reads values from HTTP headers.

Automatic Underscore to Hyphen Conversion

HTTP headers use hyphens (e.g., User-Agent), but Python variables can’t contain hyphens. FastAPI automatically converts underscores to hyphens:
user_agent parameter automatically matches the User-Agent header.

Disable Automatic Conversion

If you need to preserve underscores, disable conversion:
Now it will only match a header literally named strange_header, not Strange-Header.

Required Header Parameters

Make headers required by not providing a default:
Requests without the required header will return a 422 validation error.

Optional Header Parameters

Make headers optional with a default value:

Header Validation

Header() supports validation parameters:
1

String Validation

Use min_length, max_length, pattern for string headers
2

Documentation

Add title, description, examples for better API docs
3

Type Conversion

Declare types like int, bool for automatic conversion

Duplicate Headers (List Values)

Some headers can appear multiple times. Receive them as a list:
For a request with:
You’ll receive:

Common Standard Headers

Authorization Header

Content-Type Header

Accept Header

User-Agent Header

Custom Headers

Read custom application headers (usually prefixed with X-):
Custom headers conventionally use the X- prefix, though this is no longer required by RFC 6648.

Header Aliases

Use aliases for headers with special naming:

Case Sensitivity

HTTP header names are case-insensitive. FastAPI handles this automatically:
All of these match:
  • User-Agent: Mozilla/5.0
  • user-agent: Mozilla/5.0
  • USER-AGENT: Mozilla/5.0

Authentication Example

Common pattern for API key authentication:

Setting Response Headers

While Header() reads headers, use Response to set them:

Header() Parameters

All available parameters:
  • Validation: min_length, max_length, pattern
  • Documentation: title, description, examples, deprecated
  • Behavior: alias, default, convert_underscores, include_in_schema

Testing Header Endpoints

Common Use Cases

1

Authentication

API keys, bearer tokens, basic auth
2

Request Tracing

Request IDs, correlation IDs for logging
3

Content Negotiation

Accept, Content-Type headers
4

Client Information

User-Agent, Accept-Language for analytics
5

API Versioning

Custom version headers for API versioning