Saturday, 11 December 2021

FastAPI: Specify headers

You can specify a header using Header function. It is almost similar to how we defined path and query parameters.

 

Example

@app.get("/demo")
def headers_demo(
    user_agent: Optional[str] = Header(None),
    content_encoding: Optional[str] = Header(None)):
    return {"user_agent" : user_agent, "content_encoding" : content_encoding}

declareRequestheaders.py

from fastapi import FastAPI, Header
from typing import Optional

app = FastAPI()

@app.get("/demo")
def headers_demo(
    user_agent: Optional[str] = Header(None),
    content_encoding: Optional[str] = Header(None)):
    return {"user_agent" : user_agent, "content_encoding" : content_encoding}

Open terminal and execute the command ‘uvicorn declareRequestHeaders:app --reload’.

$ uvicorn declareRequestHeaders:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [25560] using statreload
INFO:     Started server process [25562]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://localhost:8000/docs’ in browser and experiment with /demo api.





 

Note

a.   Most of the standard request header names are separated by – (hyphen) character (Ex: user-agent). But python do not allow – character in variable names, so FastApi will convert the parameter names characters from underscore (_) to hyphen (-) to extract and document the headers.

b.   To disable this automatic underscore conversion, pass the argument convert_underscores and set the value to false.

Ex: Header(None, convert_underscores=False)

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment