Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

879
Views
How to check if a cookie is set in FastAPI?

I defined an optional cookie parameter and now want to check if the cookie was set. Unfortunately, the variable does not equal to None but to an empty Cookie object. How can I check the cookie object if it is set?
Here's how I defined the cookie parameter:

@app.route("/graphcall")
def graphcall(request: Request, ads_id: Optional[str] = Cookie(None)):
    if ads_id:
      # Do stuff if the ads_id is set
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

I assume you tried this via SwaggerUI. Setting Cookie values currently does not work via SwaggerUI due to browser security restrictions.

@app.get("/items/")
async def read_items(ads_id: Optional[str] = Cookie(None)):
    if ads_id:
        answer = "set to %s" % ads_id
    else:
        answer = "not set"
    return {"ads_id": answer}

works perfectly from command line with Fastapi 0.61.0

$ curl -X GET "http://127.0.0.1:8000/items/" -H  "accept: application/json" -H  "Cookie: ads_id=foobar"
{"ads_id":"set to foobar"}

$ curl -X GET "http://127.0.0.1:8000/items/" -H  "accept: application/json"
{"ads_id":"not set"}
over 4 years ago · Santiago Trujillo Report

0

For me this works

async def setcookie(request: Request, nm: str = Form(...)):
    print("setcookie "+nm)
    response = templates.TemplateResponse("readcookie.html",{"request": request})
    response.set_cookie(key="userID", value=nm)

@app.get("/getcookie/", response_class=HTMLResponse)
async def getcookie(request: Request,userID: Optional[str] = Cookie(None)):
    if userID:
        print("getcookie "+userID)
    else:
        print("getcookie None")
    return templates.TemplateResponse("showcookie.html", {"request": request, "name": userID})

In getcookie I have the cookie set in setcookie.

I follow this approach:

https://fastapi.tiangolo.com/advanced/response-cookies/#return-a-response-directly

over 4 years ago · Santiago Trujillo Report

0

I still don't understand why the Optional[str] = Cookie(None) method didn't work. For me this way worked

@router.post('/login')
async def sign_in(
        user_data: OAuth2PasswordRequestForm = Depends(),
        service: AuthService = Depends(),
):
    session = await service.authenticate_user(
        user_data.username,
        user_data.password
    )
    response = RedirectResponse(url='/')
    response.set_cookie('Authorization', value=session['session_id'], httponly=True)
    return response


async def get_current_user(request: Request): 
    try:
        cookie_authorization: str = request.cookies.get("Authorization")
        # some logic with cookie_authorization
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="Invalid authentication"
        )
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!