Skip to content
tezvyn:
Menu

Declaring Request Headers in FastAPI

Source: fastapi.tiangolo.comEasyHow cards are made

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.

Interview question

Which scenario is least suitable for declaring individual HTTP headers using Header() in a FastAPI path operation?

  • a.Handling a full OAuth2 authentication and authorization flow.Correct
  • b.Accessing a specific X-Request-ID for tracing a request.
  • c.Implementing a simple API key check using an X-API-Key header.
  • d.Retrieving a client's User-Agent for logging purposes.
Why?

The card explicitly advises against using Header() for complex authentication schemes like OAuth2, as FastAPI provides dedicated security utilities for such cases. It is well-suited for simpler tasks like reading User-Agent, API keys, or tracing IDs.

Just read this? Test yourself on what you have been reading.

Read the original → fastapi.tiangolo.com

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on python — each one lists the topics its interview covers.

See open roles