Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

876
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda