Path parameters are dynamic variables embedded directly inside a URL path using curly braces
{}to identify specific resources, such as/users/{user_id}.When a client sends a value with the wrong data type (like passing text instead of an integer), FastAPI automatically blocks the request and returns a 422 Unprocessable Entity HTTP error along with a structured JSON explanation.
How Path Parameters Work
We define a path parameter by placing a variable name inside
{}in the route decorator, then declaring an argument with the exact same name and a Python type hint in the function.
from fastapi import FastAPI
app = FastAPI()
@app.get("/orders/{order_id}")
async def get_order(order_id: int):
return {"order_id": order_id}What Happens When the Wrong Type Is Sent?
Suppose a client requests
/orders/abcon the endpoint. Because"abc"cannot be converted into an integer, FastAPI stops execution before your function ever runs.HTTP Status Code. FastAPI immediately responds with
422 Unprocessable Entity.Detailed JSON Error Payload. The response tells the client exactly where the error occurred, what value was received and what type was expected.
{
"detail": [
{
"type": "int_parsing",
"loc": [
"path",
"order_id"
],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "abc"
}
]
}