
FastAPI
Learn essential concepts of validation in FastAPI.
This section covers path parameter validation, including:
FastAPI allows you to validate path parameters using constraints. This ensures only valid data reaches your endpoint handlers.
from fastapi import FastAPI, Path
app = FastAPI()
# Minimum and maximum values
@app.get("/items/{item_id}")
async def get_item(item_id: int = Path(..., gt=0)):
# item_id must be greater than 0
# /items/0 ❌ Validation error
# /items/1 ✅ Valid
return {"item_id": item_id}
# Range validation
@app.get("/products/{product_id}")
async def get_product(product_id: int = Path(..., ge=1, le=1000)):
# product_id must be between 1 and 1000 (inclusive)
return {"product_id": product_id}
# Multiple parameters with validation
@app.get("/users/{user_id}/posts/{post_id}")
async def get_user_post(
user_id: int = Path(..., gt=0, description="The user ID"),
post_id: int = Path(..., gt=0, description="The post ID")
):
return {"user_id": user_id, "post_id": post_id}
# Float range
@app.get("/ratings/{rating}")
async def rate_item(rating: float = Path(..., ge=0.0, le=5.0)):
# Rating between 0 and 5
return {"rating": rating}from fastapi import FastAPI, Path
import re
# String length
@app.get("/users/{username}")
async def get_user(username: str = Path(..., min_length=3, max_length=20)):
# Username must be 3-20 characters
return {"username": username}
# Regular expression pattern
@app.get("/files/{file_name}")
async def download_file(
file_name: str = Path(
...,
regex="^[a-zA-Z0-9_-]+\\.pdf$" # Only valid PDF filenames
)
):
# Only accepts: document.pdf, file_123.pdf, etc.
# Rejects: document.txt, invalid!.pdf
return {"file_name": file_name}
# Email-like slug validation
@app.get("/posts/{slug}")
async def get_post(
slug: str = Path(..., regex="^[a-z0-9-]+$", min_length=5)
):
# Slug must be lowercase alphanumeric with hyphens
return {"slug": slug}# Invalid path parameter returns 422
# GET /items/abc → Status 422 Unprocessable Entity
# Response: {
# "detail": [
# {
# "loc": ["path", "item_id"],
# "msg": "value is not a valid integer",
# "type": "type_error.integer"
# }
# ]
# }
# Constraint violation
# GET /items/0 (with gt=0 constraint) → Status 422
# Response: {
# "detail": [
# {
# "loc": ["path", "item_id"],
# "msg": "ensure this value is greater than 0",
# "type": "value_error.number.not_gt",
# "ctx": {"limit_value": 0}
# }
# ]
# }Path validation is essential for:
Next step: Explore the advanced section for production patterns and optimization techniques.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward