Query Parameter validation using Pydantic Model in FastAPI

Query Parameter Validation Using Pydantic In FastApi

In the last post we saw how to perform validation using Dependency Injection function, but in this post, we will see how to write a simple pydantic model and use it as a dependency object for the query path validation.

Creating Pydantic Model Class

Let’s create a pydantic class named “SemesterClass”, it declared three variables

  • course
  • semester and
  • strength
class SemisterClass(BaseModel):
    course: str = Query(..., title="Course", description="Course Name")
    semester: int = Query(..., title="Skip", description="Number of semester", ge=1, le=8)
    strength: int = Query(10, title="Total Student", description="Total number of student in each semester:", ge=1, le=60)

These variables are defined with Query construct for validation, validation are below:

  • Course: defined with three dots, which make it mandatory required filed.
  • Semester: it is also mandatory required field defined with three dots also the value it will hold is of int datatype and value should be greater than equal to 1 and less then equal to 8.
  • Strength: The default value for this field is 10 and have a range of 1 to 60

Writing get wrapper Method:

Now we will write a get wrapper method which will define a path argument of SemisterClass type and add a dependency injection to it, snippet below.

@app.get("/semester/")
async def read_semester(detail: SemisterClass = Depends()):
    """
       Get the course, semester and strength detail by calling the read_semester wrapped method under get action
    """
    return {"course": detail.course, "semester": detail.semester, "strength": detail.strength}

Here you can see with “detail” parameter object of SemisterClass we can access the variable defined in the SemesterClass Model. Like detail.course or detail.semester.

Complete Code below:

from fastapi import Depends, FastAPI, Query
from pydantic import BaseModel

app = FastAPI()


class SemisterClass(BaseModel):
    course: str = Query(..., title="Course", description="Course Name")
    semester: int = Query(..., title="Skip", description="Number of semester", ge=1, le=8)
    strength: int = Query(10, title="Total Student", description="Total number of student in each semester:", ge=1, le=60)


@app.get("/semester/")
async def read_semester(detail: SemisterClass = Depends()):
    """
    Get a list of items with optional skip and limit query parameters.
    - item: Pydantic model containing skip and limit attributes.
    """
    return {"course": detail.course, "semester": detail.semester, "strength": detail.strength}

Testing on SwaggerUI:

Here if you see, it takes three parameter which are defined in the Pydantic Model and also applied the validation, which you can see in the highlighted selection and then it produce json response of the value passed.

Thank you, in the next post we will try to sub dependency for validation of endpoints parameters.

Happy Coding!

Leave a Reply

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