Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Path Parameter Basics📚 Path Types📚 Validation📚 Required vs Optional📚 Path Converters📚 Order Matters📚 Complex Paths
Fastapi/Path Parameters/Validation

Validation

Learn essential concepts of validation in FastAPI.

What You'll Learn

This section covers path parameter validation, including:

  • Using constraints (min, max, regex)
  • Numeric value validation
  • String length validation
  • Custom validation patterns

Core Concepts

FastAPI allows you to validate path parameters using constraints. This ensures only valid data reaches your endpoint handlers.

Numeric Constraints

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}

String Validation

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}

Validation Error Responses

# 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}
#     }
#   ]
# }

Real-World Usage

Path validation is essential for:

  • **API security**: Prevent invalid data from reaching handlers
  • **Data integrity**: Ensure constraints are met
  • **User feedback**: Clear validation error messages
  • **Documentation**: Swagger UI shows constraints automatically

🔑 Key Takeaways

  • ✅ Understand the purpose of validation
  • ✅ Know when to apply this pattern
  • ✅ Follow best practices consistently
  • ✅ Test thoroughly in production scenarios

Next step: Explore the advanced section for production patterns and optimization techniques.


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn