0
0
FastAPIframework~5 mins

Path parameter types and validation in FastAPI

Choose your learning style9 modes available
Introduction

Path parameters let you get values from the URL. Using types and validation helps make sure these values are correct before your app uses them.

When you want to get an ID or name from the URL to find a specific item.
When you need to make sure a number in the URL is positive or within a range.
When you want to accept only certain types of values in the URL to avoid errors.
When you want to automatically convert URL parts to the right data type like int or float.
When you want to give clear error messages if the URL value is wrong.
Syntax
FastAPI
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', ge=1, le=1000)):
    return {'item_id': item_id}

Use Python type hints to declare the expected type of the path parameter.

Use Path() to add validation rules like minimum (ge) and maximum (le) values.

Examples
This example expects user_id as an integer from the URL path.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get('/users/{user_id}')
async def get_user(user_id: int):
    return {'user_id': user_id}
This example adds validation to ensure product_id is at least 1.
FastAPI
from fastapi import FastAPI, Path

app = FastAPI()

@app.get('/products/{product_id}')
async def get_product(product_id: int = Path(..., ge=1)):
    return {'product_id': product_id}
This example expects a string path with length between 3 and 50 characters.
FastAPI
from fastapi import FastAPI, Path

app = FastAPI()

@app.get('/files/{file_path}')
async def read_file(file_path: str = Path(..., min_length=3, max_length=50)):
    return {'file_path': file_path}
Sample Program

This FastAPI app defines a path parameter order_id that must be an integer between 1 and 9999. If the value is outside this range or not an integer, FastAPI will return an error automatically.

FastAPI
from fastapi import FastAPI, Path

app = FastAPI()

@app.get('/orders/{order_id}')
async def read_order(order_id: int = Path(..., title='Order ID', ge=1, le=9999)):
    return {'order_id': order_id}
OutputSuccess
Important Notes

FastAPI automatically converts path parameters to the declared type or returns an error if conversion fails.

Validation parameters like ge (greater or equal) and le (less or equal) help keep data safe and predictable.

Use descriptive titles in Path() to improve API documentation readability.

Summary

Path parameters get values from the URL and can be typed for safety.

Use Path() to add validation rules like minimum and maximum values.

FastAPI handles errors automatically if the path parameter is missing or invalid.