Search code examples
pythonhttpcookiesfastapistarlette

How to get the cookies from an HTTP request using FastAPI?


Is it possible to get the cookies when someone hits the API? I need to read the cookies for each request.

@app.get("/")
async def root(text: str, sessionKey: str = Header(None)):
    print(sessionKey)
    return {"message": text+" returned"}

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=5001 ,reload=True)

Solution

  • You can do it in the same way you are accessing the headers in your example (see docs):

    from fastapi import Cookie
    
    @app.get("/")
    async def root(text: str, sessionKey: str = Header(None), cookie_param: int | None = Cookie(None)):
        print(cookie_param)
        return {"message": f"{text} returned"}