Header() function.
Basic Header Parameter
UseHeader() 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:strange_header, not Strange-Header.
Required Header Parameters
Make headers required by not providing a default: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 headers2
Documentation
Add
title, description, examples for better API docs3
Type Conversion
Declare types like
int, bool for automatic conversionDuplicate Headers (List Values)
Some headers can appear multiple times. Receive them as a list:Common Standard Headers
Authorization Header
Content-Type Header
Accept Header
User-Agent Header
Custom Headers
Read custom application headers (usually prefixed withX-):
Header Aliases
Use aliases for headers with special naming:Case Sensitivity
HTTP header names are case-insensitive. FastAPI handles this automatically:User-Agent: Mozilla/5.0user-agent: Mozilla/5.0USER-AGENT: Mozilla/5.0
Header() vs Cookie() vs Query()
Authentication Example
Common pattern for API key authentication:Setting Response Headers
WhileHeader() 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
Related Topics
- Cookie Parameters - Read HTTP cookies
- Query Parameters - Read URL parameters
- Request Body - Handle request data