How to check if a cookie is set in fastapi?

Member

by jerad , in category: Javascript , 11 days ago

How to check if a cookie is set in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 10 days ago

@jerad 

In FastAPI, you can check if a cookie is set by accessing the request parameter in one of your route functions and using its cookies attribute. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/get-cookie")
async def get_cookie(request: Request):
    cookie_name = "my_cookie"
    
    if cookie_name in request.cookies:
        return {"message": "Cookie is set"}
    else:
        return {"message": "Cookie is not set"}


In this example, the get_cookie function takes a Request object as a parameter, which allows you to access the cookies sent with the request through the cookies attribute. The function then checks if the specified cookie name is in the request cookies. If the cookie is set, it returns a message indicating that the cookie is set; otherwise, it returns a message indicating that the cookie is not set.