Sunday 12 December 2021

FastAPI: Declare a header with multiple values

To declare a header with multiple values, define the header with list type declaration.

 

Example

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

 

Find the below working application.

 

headerWithMultipleValues.py

 

from fastapi import FastAPI, Header
from typing import Optional, List

app = FastAPI()

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

 

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

 

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

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

 


 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment