Home > Enterprise >  How get the cookies from HTTP request using FastAPI?
How get the cookies from HTTP request using FastAPI?

Time:07-29

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)

CodePudding user response:

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"}

CodePudding user response:

Option 1

Use the Request object to get the cookies, as described in Starlette documentation.

from fastapi import Request

@app.get("/")
def root(request: Request):
    print(request.cookies)
    print(request.cookies.get('sessionKey'))

Option 2

Use the Cookie parameter, as described in FastAPI documentation.

from fastapi import Cookie

@app.get("/")
def root(sessionKey: str = Cookie(default=None)):
    print(sessionKey)
  • Related