Categories
Tags
30days AI ai backend blog blogging booking burnout career chatbot cms coding design development devops django docker email express fastapi flight Flight Booking System full stack full-stack gmail GPT-3 interviews journey LinkedIn MERN mongodb NextJS nextjs notion OpenAI openai planning portfolio programming project python react ReactJS search sendgrid smtp software software development tailwind
251 words
1 minutes
Day 5 of 30 Days of FastAPI - Path and Query Validation - Beyond Type Hinting
On Day 4, we saw how Pydantic ensures we get a str or an int. Today, we explore how to add Constraints. FastAPI provides the Query, Path, and Body classes to add validation and metadata to your parameters.
1. Validating Query Parameters
Suppose you have a search endpoint. You want to make sure the search term q is at least 3 characters but no more than 50.
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(
q: str | None = Query(
None,
min_length=3,
max_length=50,
pattern="^fixedquery$", # regex pattern to match
title="Search Query",
description="Search for items in the database"
)
):
return {"q": q}

2. Validating Path Parameters
The Path class works similarly but for the variables inside your URL. You can enforce numeric constraints like gt (greater than) or le (less than or equal to).
from fastapi import FastAPI, Path
@app.get("/items/{item_id}")
async def read_item(
item_id: int = Path(..., title="The ID of the item", gt=0, le=1000)
):
return {"item_id": item_id}

3. Why Metadata Matters
By adding title and description, your Swagger UI (/docs) becomes a complete manual. Any developer using your API will see the exact constraints (e.g., โMinimum length: 3โ) without you writing a single word of external documentation.
๐ ๏ธ Implementation Checklist
- Added
min_lengthvalidation to a string query. - Added
gt(greater than) validation to a numeric path parameter. - Added a custom
descriptionto an endpoint parameter. - Verified that a
422 Unprocessable Entityerror is returned when rules are broken.
๐ Resources
- Documentation: FastAPI Path Parameters and Numeric Validation
- Documentation: FastAPI Query Parameters and String Validation
- Course: FastAPI โ FreeCodeCamp
Day 5 of 30 Days of FastAPI - Path and Query Validation - Beyond Type Hinting
https://beyond400.vercel.app/posts/fastapi-05/
