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