0
votes

Is this possible to get the cookies when someone hits the API? 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)
2

2 Answers

0
votes

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

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)