Skip to main content

Query Parameters-With-Models

Query Parameter with models

What is Query Parameter Model ?

In FastAPI, a query parameter model is a way to group and validate multiple query parameters using a Pydantic model. This is especially useful when you have many related query parameters and want to keep your endpoint functions clean and organized.

Why Use Query Parameter Model ?

  • Keeps your code cleaner and more maintainable
  • Enables reusability of validation logic
  • Automatically generates OpenAPI documentation
  • Supports default values, type checking, and validation rules

1. Without a Model

from fastapi import FastAPI
app = FastAPI()

@app.get("/items/")
def get_items(skip: int = 0, limit: int = 10, search: str = None):
return {"skip": skip, "limit": limit, "search": search}

2. With a query parameter model

from fastapi import FastAPI, Depends
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

class ItemQueryParams(BaseModel):
skip: int = 0
limit: int = 10
search: Optional[str] = None

@app.get("/items/")
def get_items(params: ItemQueryParams = Depends()):
return params

Depends() tells FastAPI to extract query parameters and validate them using the ItemQueryParams model. FastAPI will automatically:

  • Parse query parameters
  • Validate types
  • Apply default values
  • Return a 422 error if validation fails