Reputation: 327
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)
Upvotes: 11
Views: 16851
Reputation: 34129
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')
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
Upvotes: 12
Reputation: 2911
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"}
Upvotes: 2