Search code examples
pythonswaggerfastapi

Headers with FastAPI


I created an endpoint which requires the User Agent as described in the documentation: https://fastapi.tiangolo.com/tutorial/header-params/#__tabbed_2_1

However, the Swagger documentation generated displays it as a query param.

enter image description here

Any ideas of what is wrong in my setup?

from typing import Annotated

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(user_agent: Annotated[str | None, Header()] = None):
    return {"User-Agent": user_agent}

I am running it with Python 3.10.


Solution

  • What version of fastapi are you running? I found the same issue when running fastapi 0.94.1

    Basically, fastapi <0.95 does not support Annotated. It will always interpret Annotated as a query parameter. The problem is: it won't throw an error because it is still valid.

    You have two options: upgrade fastapi to >=0.95 or use the non-annotated version

    @app.get("/items/")
    async def read_items(user_agent: str | None = Header(default=None)):
        return {"User-Agent": user_agent}