0
0
FastapiHow-ToBeginner · 3 min read

How to Validate Path Parameters in FastAPI

In FastAPI, you validate path parameters by declaring their type in the function signature using Python type hints, such as int or str. You can also add validation constraints like Path(..., gt=0) to enforce rules such as greater than zero.
📐

Syntax

To validate a path parameter in FastAPI, declare it in the path operation function with a type hint and optionally use Path from fastapi to add validation rules.

  • param: type - declares the parameter and its expected type.
  • Path(..., constraints) - adds validation like minimum, maximum, regex, or description.
python
from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int = Path(..., gt=0, lt=1000)):
    return {"item_id": item_id}
💻

Example

This example shows a FastAPI endpoint that accepts an item_id path parameter. It must be an integer greater than 0 and less than 1000. If the value does not meet these rules, FastAPI returns a clear error message automatically.

python
from fastapi import FastAPI, Path
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int = Path(..., gt=0, lt=1000)):
    return {"item_id": item_id}

client = TestClient(app)

# Valid request
response_valid = client.get("/items/10")

# Invalid request (item_id too low)
response_invalid = client.get("/items/0")

print("Valid response status:", response_valid.status_code)
print("Valid response JSON:", response_valid.json())
print("Invalid response status:", response_invalid.status_code)
print("Invalid response JSON:", response_invalid.json())
Output
Valid response status: 200 Valid response JSON: {'item_id': 10} Invalid response status: 422 Invalid response JSON: {'detail':[{'loc':['path','item_id'],'msg':'ensure this value is greater than 0','type':'value_error.number.gt','ctx':{'limit_value':0}}]}
⚠️

Common Pitfalls

Common mistakes when validating path parameters in FastAPI include:

  • Not using type hints, which disables automatic validation.
  • Using query parameter validators like Query instead of Path for path parameters.
  • Forgetting to import Path from fastapi.
  • Setting conflicting constraints that make no sense (e.g., gt=10 and lt=5).
python
from fastapi import FastAPI

app = FastAPI()

# Wrong: no type hint, no validation
@app.get("/users/{user_id}")
async def get_user(user_id):
    return {"user_id": user_id}

# Correct: with type hint and Path validation
from fastapi import Path

@app.get("/users/{user_id}")
async def get_user(user_id: int = Path(..., gt=0)):
    return {"user_id": user_id}
📊

Quick Reference

Use this quick guide to validate path parameters in FastAPI:

  • Type hint: Declare the expected type (e.g., int, str).
  • Path function: Use Path(..., constraints) for validation rules.
  • Common constraints: gt (greater than), lt (less than), ge (greater or equal), le (less or equal), regex (pattern matching).
  • Errors: FastAPI returns 422 status with details if validation fails.

Key Takeaways

Always use Python type hints to enable FastAPI's automatic path parameter validation.
Use fastapi.Path with constraints like gt, lt, regex to enforce rules on path parameters.
FastAPI returns clear 422 error responses when path parameter validation fails.
Avoid mixing query parameter validators with path parameters; use Path for path params.
Test your endpoints with valid and invalid inputs to confirm validation works as expected.