FastAPI Headers implementation

Programming Image
    What are API headers
    
    API headers are like an extra Source of information for each api call you make.
    Their job is to represent the meta-data associated with api request and response.
    
    How to implement headers in FastAPI
    
    You can define Header params just the same way you define Query, Path, Cookie params in FastAPI.
    
    Import Header
    
    First import Header:

    Python 3.9

    from fastapi import FastAPI, Header
    
    app = FastAPI()
    
    
    @app.get("/headers")
    async def read_headers(x_token: Optional[str] = Header(default=None)):
        return {"x-token": x_token}
    
    Declare Header Parameters
    
    You should declare the header params using same structure as with Path, Query or Cookie.
    from typing import Optional
    
    from fastapi import FastAPI, Header
    
    app = FastAPI()
    
    
    @app.get("/headers")
    async def read_headers(x_token: Optional[str] = Header(default=None), user_agent: str = Header(default="My User Agent 1.0")):
        return {"x-token": x_token, "user-agent": user_agent}
    Automatic conversion

    Most headers are separated by a hypen character, also known as the minus symbol (-).

    But a variable like x-token is invalid in python.

    So by default Header will convert the parameter names from underscore (_) to hypen to extract and document the headers.

    Also note HTTP headers are case sensitive, so you can declare them with standard Python style.

    If for some any reasons you need to disable automatic conversion of underscore to hypens, set the parameter convert_underscore of Header to False:

    from typing import Optional
    
    from fastapi import FastAPI, Header
    
    app = FastAPI()
    
    
    @app.get("/headers")
    async def read_headers(x_token: Optional[str] = Header(default=None, convert_underscores=False), user_agent: str = Header(default="My User Agent 1.0")):
        return {"x-token": x_token, "user-agent": user_agent}

     

    Duplicate Headers

    We can have duplicate headers why by same header with multiple values. You can define this by using a list in the type declaration. You will receive all the values from duplicate header as a Python list.

    See below sample.

    import uvicorn
    from fastapi import FastAPI, Header
    
    app = FastAPI()
    
    
    @app.get("/headers")
    async def read_headers(x_token: list[str] = Header(default=None), user_agent: str = Header(default="My User Agent 1.0")):
        return {"x-token": x_token, "user-agent": user_agent}
    
    if __name__ == '__main__':
        uvicorn.run(app, host='127.0.0.1', port=8000)

    How to input the the list of header values in FastAPI Swagger UI

    For the above after execution see below headers response

    {
      "x-token": [
        "oa,da,tokenid"
      ],
      "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"
    }

     

    In Summary:

    Declare headers with Header and dont worry about underscore in your variables, FastAPI will take care of coverting them to hypen.

    Get the code implementation Here

     

    0 Comments

    To add a comment, please Signup or Login

    OR