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

Question:

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)
Asked By: Praveen K M

||

Answers:

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"}
Answered By: M.O.

Option 1

Use the Request object to get the cookie you wish, as described in Starlette documentation.

from fastapi import Request

@app.get('/')
async def root(request: Request):
    return request.cookies.get('sessionKey')

Option 2

Use the Cookie parameter, as described in FastAPI documentation. On a side note, the example below defines the cookie parameter as optional, using the type Union[str, None]; however, there are other ways doing that as well (e.g., str | None in Python 3.10+)—have a look at this answer and this answer for more details.

from fastapi import Cookie
from typing import Union

@app.get('/')
async def root(sessionKey: Union[str, None] = Cookie(None)):
    return sessionKey
Answered By: Chris