FastAPI - Header Parameters

In order to read the values of an HTTP header that is a part of the client request, import the Header object from the FastAPI library, and declare a parameter of Header type in the operation function definition. The name of the parameter should match with the HTTP header converted in camel_case.

In the following example, the "accept-language" header is to be retrieved. Since Python doesn’t allow "-" (dash) in the name of identifier, it is replaced by "_" (underscore)

from typing import Optional
from fastapi import FastAPI, Header
app = FastAPI()
async def read_header(accept_language: Optional[str] = Header(None)):
   return {"Accept-Language": accept_language} 

As the following Swagger documentation shows, the retrieved header is shown as the response body.

FastAPI Header Parameters

You can push custom as well as predefined headers in the response object. The operation function should have a parameter of Response type. In order to set a custom header, its name should be prefixed with "X". In the following case, a custom header called "X-Web-Framework" and a predefined header “Content-Language" is added along with the response of the operation function.

from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
def set_rsp_headers():
   content = {"message": "Hello World"}
   headers = {"X-Web-Framework": "FastAPI", "Content-Language": "en-US"}
   return JSONResponse(content=content, headers=headers)

The newly added headers will appear in the response header section of the documentation.

FastAPI Header Parameters