Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

880
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda