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

184
Visualizações
dependency injection data model fastapi

I'm very new to fastapi. I've a request which looks something like this

@router.post("/", response_model=EducationInResp)
async def create_Education_account(
        education_in: EducationCreation,
        current_user=Depends(get_current_user),
        has_perm=Depends(user_has_create_perms),
):

Now the EducationCreation data model has a field called customer_id

I want to check if the customer id exists in the database. Now I know that I can manually do that within the function itself and it's not recommended to do database related validation in Schema. Is there any way to check if the customer id exists in the database using dependencies. Is there something like this?

async def check_customer_exist(some_val):
    # some operation here to check and raise exception

@router.post("/", response_model=EducationInResp)
async def create_Education_account(
        education_in: EducationCreation = Depends(check_customer_exist),
        current_user=Depends(get_current_user),
        has_perm=Depends(user_has_create_perms),
):
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You could do that by declaring the parameter in the dependency function, as described in the documentation. If the customer_id exists in the database, then return the data to the route. If not, you could then raise an HTTPException, or handle it as desired.

from fastapi.exceptions import HTTPException
  
customer_ids = [1, 2, 3]

async def check_customer_exist(education_in: EducationCreation):
    if education_in.customer_id not in customer_ids:  # here, check if the customer id exists in the database. 
        raise HTTPException(status_code=404, detail="Customer ID not found")
    else:
        return education_in

@router.post("/", response_model=EducationInResp)
async def create_Education_account(
        education_in: EducationCreation = Depends(check_customer_exist),
        current_user=Depends(get_current_user),
        has_perm=Depends(user_has_create_perms),
):
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