tezvyn:

Declaring Request Headers in FastAPI

AI-drafted, machine-checkedSource: fastapi.tiangolo.combeginner

Treat request headers like any other parameter in FastAPI. Declare them in your function signature to access values like `User-Agent` or `X-Token`. FastAPI automatically converts hyphens to underscores, so `User-Agent` is accessed via the `user_agent`…

WHY IT EXISTS Web applications often need to read HTTP headers to understand the client's request, for tasks like authentication, content negotiation, or logging. FastAPI provides a declarative way to access these headers, integrating them directly into its validation and dependency injection system, which avoids manual request parsing.

THE MENTAL MODEL Think of a request header as just another input to your endpoint, like a URL path parameter or a query string. By declaring it in your function's argument list using Header(), you tell FastAPI to find that header, extract its value, validate it, and pass it to your code.

HOW IT WORKS First, you import Header from fastapi. In your path operation function, add an argument with a type hint and a default value of Header(). For example: user_agent: str | None = Header(default=None). FastAPI uses the variable name to find the corresponding header. It automatically converts hyphens to underscores, so a parameter named user_agent will receive the value of the User-Agent header. If a header is sent multiple times, FastAPI collects all values into a list.

WHEN TO USE IT Use this for reading standard headers like User-Agent or Accept-Language. It's also perfect for custom headers used for simple API keys (X-API-Key), tracing IDs (X-Request-ID), or client-side versioning (X-App-Version).

WHEN NOT TO USE IT Avoid this for complex authentication schemes like OAuth2, which have dedicated security utilities in FastAPI. If you need to access all headers or the raw request object, you should inject the Request object directly instead of declaring individual headers.

ONE CANONICAL EXAMPLE To read the User-Agent header, your endpoint would look like this: async def get_items(user_agent: str | None = Header(default=None)): return {"User-Agent": user_agent}. If a client sends a request with the header User-Agent: my-app/1.0, the user_agent variable in your function will contain the string "my-app/1.0". If the header is missing, it will be None.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.