Understanding Paths, Parameters, and Validation in FastAPI
Modern web frameworks, including FastAPI, use routes or endpoints as part of the URL instead of file-based URLs. This approach makes URLs easier to remember and more meaningful for users. In FastAPI, a path or route refers to the part of the URL that comes after the first slash (/).
What is a Path in FastAPI?
Consider the URL:
http://localhost:8000/hello/TutorialsPoint
Here, the path is:
/hello/TutorialsPoint
In FastAPI, you define paths using operation decorators, which correspond to HTTP verbs like GET, POST, PUT, or DELETE. The decorator is followed by a function called a path operation function, which executes when the URL is visited.
Example: Basic Path Operation
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
return {"message": "Hello World"}
"/"→ the pathget→ the HTTP operation@app.get("/")→ path operation decoratorindex()→ path operation function
HTTP Methods in FastAPI
| Method | Description |
|---|---|
| GET | Retrieve data from the server (most common) |
| HEAD | Like GET but without the response body |
| POST | Send data to the server, typically form data |
| PUT | Replace the current representation of a resource |
| DELETE | Remove the resource identified by the URL |
The async keyword allows the function to run asynchronously, without blocking other requests, though it’s optional.
Path Parameters
Paths can contain variable parameters, which allow URLs to accept dynamic data. Parameters are enclosed in curly braces {}.
Example: Single Path Parameter
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello/{name}")
async def hello(name):
return {"name": name}
URL: http://localhost:8000/hello/Tutorialspoint
{"name":"Tutorialspoint"}
Change Tutorialspoint to Python:
{"name":"Python"}
Multiple Path Parameters
@app.get("/hello/{name}/{age}")
async def hello(name, age):
return {"name": name, "age": age}
URL: http://localhost:8000/hello/Ravi/20
{"name":"Ravi","age":"20"}
Path Parameters with Type Hints
@app.get("/hello/{name}/{age}")
async def hello(name: str, age: int):
return {"name": name, "age": age}
URL: http://localhost:8000/hello/20/Ravi → Error because age must be an integer.
Query Parameters
Query parameters are sent in the URL after a ? using key-value pairs.
http://localhost:8000/hello?name=Ravi&age=20
FastAPI function:
@app.get("/hello")
async def hello(name: str, age: int):
return {"name": name, "age": age}
Validation on Parameters
FastAPI allows validation on path and query parameters using the Path and Query classes.
Example: Validating a String Path Parameter
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/hello/{name}")
async def hello(name: str = Path(..., min_length=3, max_length=10)):
return {"name": name}
If name is shorter than 3 or longer than 10 characters, FastAPI returns:
{
"detail": [
{
"type": "string_too_long",
"loc": ["path", "name"],
"msg": "String should have at most 10 characters",
"input": "Tutorialspoint",
"ctx": {"max_length": 10}
}
]
}
Numeric Validation Example
from fastapi import FastAPI, Path
@app.get("/hello/{name}/{age}")
async def hello(
*,
name: str = Path(..., min_length=3, max_length=10),
age: int = Path(..., ge=1, le=100)
):
return {"name": name, "age": age}
URL: http://localhost:8000/hello/hi/110 → Validation error for both name and age.
Query Parameter Validation
from fastapi import FastAPI, Path, Query
@app.get("/hello/{name}/{age}")
async def hello(
*,
name: str = Path(..., min_length=3, max_length=10),
age: int = Path(..., ge=1, le=100),
percent: float = Query(..., ge=0, le=100)
):
return {"name": name, "age": age, "percent": percent}
URL: http://localhost:8000/hello/Ravi/20?percent=79
{"name": "Ravi", "age": 20, "percent": 79}
Conclusion
FastAPI makes it easy to:
- Define path and query parameters
- Apply type hints and validation rules
- Return JSON responses automatically
- Explore APIs interactively via OpenAPI (Swagger UI)
This ensures APIs are robust, easy to use, and self-documenting, making FastAPI ideal for modern web development.