Fastapi Path Params
Path parameters are the dynamic parts of a URL path, declared using curly braces `{}`. FastAPI automatically passes path parameters to the path operation function and performs data conversion and validation based on type annotations.
* * *
## Basic Usage
Declare path parameters using Python formatted string syntax:
## Example
from fastapi import FastAPI
app = FastAPI()
# {item_id} is a path parameter
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return{"item_id": item_id}
Access **http://127.0.0.1:8000/items/5**, returns:
{"item_id": 5}
Note that the returned `item_id` is the integer `5`, not the string `"5"`. FastAPI automatically converts the string in the URL to an integer via the type annotation `item_id: int`.
* * *
## Data Conversion
When you declare the type as `int`, FastAPI automatically performs type conversion:
# Passing an integer, works normally GET /items/3 -> {"item_id": 3}# Passing a non-integer, returns a validation error GET /items/foo -> Error: Input should be a valid integer # Passing a float, also returns an error GET /items/4.2 -> Error: Input should be a valid integer
When accessing **http://127.0.0.1:8000/items/foo**, FastAPI returns the following validation error message:
{ "detail": [ { "type": "int_parsing", "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo" } ]}
> FastAPI's validation error messages are very clear, indicating the specific error location (`loc`), error type (`type`), and error description (`msg`). This is very useful for debugging.
* * *
## Types of Path Parameters
Besides `int`, you can also use other standard Python types:
| Type | Description | URL Example |
| --- | --- | --- |
| `str` | String (default type) | `/items/foo` |
| `int` | Integer | `/items/5` |
| `float` | Float | `/items/5.5` |
| `bool` | Boolean | `/items/true` |
| `uuid.UUID` | UUID | `/items/3fa85f64-5717-4562-b3fc-2c963f66afa6` |
* * *
## Path Order Matters
When multiple routes might match the same URL, the order of definition determines the matching result. FastAPI matches routes in the order they are defined, and the first matching route will be executed.
## Example
from fastapi import FastAPI
app = FastAPI()
# Must be defined before /users/{user_id}
@app.get("/users/me")
async def read_user_me():
"""Get current user info"""
return{"user_id": "the current user"}
@app.get("/users/{user_id}")
async def read_user(user_id: str):
"""Get user info by ID"""
return{"user_id": user_id}
If `/users/me` is placed after `/users/{user_id}`, then when accessing `/users/me`, FastAPI will consider `"me"` as the value of `user_id`, thus matching the wrong function.
> Routes with fixed paths must be placed before routes with dynamic path parameters, otherwise the dynamic parameter will "swallow" the value of the fixed path.
* * *
## Path Parameters with Preset Values (Enum)
When you need to limit a path parameter to a few fixed values, you can use Python's `Enum` type:
## Example
from enum import Enum
from fastapi import FastAPI
# Create an enum class, inheriting from str and Enum
class ModelName(str, Enum):
alexnet ="alexnet"
resnet ="resnet"
lenet ="lenet"
app = FastAPI()
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
# Can be compared with enum members
if model_name is ModelName.alexnet:
return{"model_name": model_name,"message": "Deep Learning FTW!"}
if model_name.value=="lenet":
return{"model_name": model_name,"message": "LeCNN all the images"}
return{"model_name": model_name,"message": "Have some residuals"}
Key points of enum classes:
| Point | Description |
| --- | --- |
| Inherit `str` | Makes the API docs recognize the value type as a string, ensuring correct rendering |
| Inherit `Enum` | Creates an enum type, limiting selectable values |
| `model_name.value` | Gets the actual value of the enum member (e.g., `"alexnet"`) |
Access **http://127.0.0.1:8000/models/alexnet**, returns:
{"model_name": "alexnet", "message": "Deep Learning FTW!"}
If a non-preset value is passed (e.g., `/models/foobar`), FastAPI will return a validation error, indicating that the selectable values are `alexnet`, `resnet`, `lenet`.
* * *
## Path Parameters Containing Paths
When you need the path parameter itself to contain a path (like a file path), use Starlette's path converter:
## Example
from fastapi import FastAPI
app = FastAPI()
# :path indicates that this parameter can match paths containing slashes
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
return{"file_path": file_path}
Access **http://127.0.0.1:8000/files/home/johndoe/myfile.txt**, returns:
{"file_path": "home/johndoe/myfile.txt"}
> Note that a double slash `//` will appear between `/files/` and `/home/` in the URL, which is normal because the path parameter starts with `/`.
* * *
## Summary
Through Python's standard type declarations, FastAPI path parameters can simultaneously provide:
* **Data Conversion**: Strings in the URL are automatically converted to the declared type
* **Data Validation**: Clear error messages are returned when types do not match
* **Automatic Documentation**: The types and constraints of path parameters automatically appear in the API documentation
* **Editor Support**: Type annotations allow you to get autocompletion in your editor
YouTip