Search code examples
pythonfastapipydantic

Dependency injection data model in FastAPI


I'm very new to FastAPI. I have 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 is 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),
):

Solution

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

    Example

    from fastapi.exceptions import HTTPException
    
    customer_ids = [1, 2, 3]
    
    
    async def check_customer_exists(ec: EducationCreation):
        # check if the customer_id exists in the database.
        if ec.customer_id not in customer_ids:
            raise HTTPException(status_code=404, detail="Customer ID not found")
        else:
            return ec
    
    
    @router.post("/")
    async def create(ec: EducationCreation = Depends(check_customer_exists)):
        pass
    

    If you would like specifying global dependencies for every endpoint in the router/app instance and would like to pass data from dependencies to the endpoint, please have a look here, as well as here and here on how to do that.