Dependency Injection Function to write complex validation in Query Parameter in FastAPI:

Dependency Injection Function in FastAPI

In the last post we saw how to perform validation using Query construct inline, but think of a situation where you need complex validation on query parameter of FastAPI, in that case you need to write your custom validator.

Via a Dependency Injection function, you can write any kind of complex validation that you want to perform on Query Parameter of FastAPI decorator methods. These Dependency Injection functions are also available for reuse in any other fastapi decorator methods. This Dependency Injection can be done by importing Depends class from fastapi.

from fastapi import Depends

Below is the code, where any number that is passed from the url need to be checked if it is even or odd, if found even it will proceed with the decorator method else it will exit with exception code.

from fastapi import Depends, FastAPI, Query
from fastapi.exceptions import HTTPException

app = FastAPI()


def check_number(number: int = Query(...)):
    if number % 2 == 1 and number > 0:
        raise HTTPException(status_code=409, detail="not even number")
    return number


@app.get("/count")
def get_count(number: int = Depends(check_number)):
    return {"even_number": number}

Here in the above code, you can see in the “/count” endpoint, it takes a number parameter as a query parameter passed to decorator method get_count. This parameter is then called by dependency function i.e., check_number_range.

Inside the def check_number, the Query Construct validator perform a validation of “Required Parameter …” then inside the dependency function it run a logic for checking even or odd, if it even it returns the passed parameter value to the decorator method but if it odd then it raises exception of 409 code with the detail “Not Even number”.

Let’s check this is SwaggerUI

Here we are trying to give odd number as parameter i.e. 3

We can see we get the response Error Status code as 409 and the response detail as “Not even number”

Now lets give a valid even parameter:

Here we can see the response code is 200 which is successful validation and the result Is json defined dictionary.

Thank you, in the next post we will try to use pydantic model for validation of endpoints parameters.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *