0
0
FastapiHow-ToBeginner · 3 min read

How to Use Path Class in FastAPI for Request Validation

In FastAPI, use the Path class to declare path parameters with validation rules and metadata. It helps you set constraints like minimum or maximum values and add descriptions for better API docs. You use it by importing Path and assigning it as a default value to a path parameter in your endpoint function.
📐

Syntax

The Path class is used to declare path parameters with validation and metadata in FastAPI. You import it from fastapi and assign it as the default value to a function parameter that matches a path variable.

Basic syntax:

from fastapi import Path

def endpoint(param: type = Path(default, *, title=None, description=None, gt=None, lt=None)):
    pass

Explanation of parts:

  • param: The name of the path parameter matching the URL path.
  • type: The expected data type (e.g., int, str).
  • default: Usually ... (Ellipsis) to mark the parameter as required.
  • title and description: Metadata for API docs.
  • gt and lt: Validation constraints for greater than and less than values.
python
from fastapi import Path

def read_item(item_id: int = Path(..., title="The ID of the item", gt=0)):
    return {"item_id": item_id}
💻

Example

This example shows a FastAPI app with a path parameter item_id that must be an integer greater than 0. The Path class adds a title and validation. If the value is invalid, FastAPI returns an error automatically.

python
from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int = Path(..., title="The ID of the item", gt=0)):
    return {"item_id": item_id}
Output
GET /items/5 -> {"item_id": 5} GET /items/0 -> 422 Unprocessable Entity (validation error)
⚠️

Common Pitfalls

  • Not using ... (Ellipsis) as the default value makes the path parameter optional, which is usually incorrect for path variables.
  • Using query parameter validators like Query instead of Path for path parameters.
  • Missing type annotations causes FastAPI to treat parameters as strings, losing validation benefits.
  • Setting conflicting validation constraints (e.g., gt=10 and lt=5) causes runtime errors.
python
from fastapi import FastAPI, Path

app = FastAPI()

# Wrong: missing Ellipsis, makes parameter optional
@app.get("/users/{user_id}")
async def read_user(user_id: int = Path(title="User ID")):
    return {"user_id": user_id}

# Right: required path parameter with validation
@app.get("/users/{user_id}")
async def read_user(user_id: int = Path(..., title="User ID", gt=0)):
    return {"user_id": user_id}
📊

Quick Reference

ParameterDescriptionExample
defaultSet to ... to make parameter requiredPath(...)
titleTitle shown in API docsPath(..., title="ID")
descriptionDescription shown in API docsPath(..., description="Item ID")
gtValue must be greater than thisPath(..., gt=0)
ltValue must be less than thisPath(..., lt=100)
geValue must be greater or equalPath(..., ge=1)
leValue must be less or equalPath(..., le=10)

Key Takeaways

Use Path(...) to declare required path parameters with validation in FastAPI.
Add metadata like title and description for better API documentation.
Use validation constraints like gt, lt, ge, and le to enforce value rules.
Always provide type annotations for path parameters to enable automatic validation.
Avoid making path parameters optional by omitting the Ellipsis ... as default.