Declaring Request Headers in FastAPI
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`…
Treat request headers just like query or path parameters. FastAPI lets you declare them directly in your function signature for automatic validation and easy access. This is useful for reading headers like `User-Agent` for analytics or a custom `X-Token` for simple auth. The main footgun is naming: FastAPI automatically converts hyphens in header names to underscores for valid Python variable names. So, to read the `User-Agent` header, your function parameter must be named `user_agent`.
Read the original → fastapi.tiangolo.com
- #python
- #fastapi
- #api
- #http
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.