FastAPI Path Parameters
Path parameters are the dynamic parts of a URL path, declared with 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's format string syntax:
Example
from
fastapi
import
FastAPI
app
=
FastAPI
(
)
{item_id} is the path parameter
@
app.
get
(
"/items/{item_id}"
)
async
def
read_item
(
item_id:
int
)
:
return
{
"item_id"
: item_id
}
Access the http://127.0.0.1:8000/items/5, returns:
{"item_id": 5}
Note that the returned item_id is an integer 5, not a string "5". FastAPI, through the type annotation, item_id: int automatically converts the string in the URL to an integer.
Data Transformation
When you declare a type of int , FastAPI automatically performs type conversion:
# 传入整数,正常工作
GET /items/3 -> {"item_id": 3}
# Return validation error if non-integer is passed
GET /items/foo -> 错误:Input should be a valid integer
# Passing a float, still throws an error
GET /items/4.2 -> 错误:Input should be a valid integer
Access the http://127.0.0.1:8000/items/foo , the validation error message returned by FastAPI:
{
"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, pointing out the exact error location (
loc), error type (type) and error description (msg). This is very useful when 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 |
Integers | /items/5 |
float |
Float (floating point number) | /items/5.5 |
bool |
Boolean | /items/true |
uuid.UUID |
UUID | /items/3fa85f64-5717-4562-b3fc-2c963f66afa6 |
Path order matters
When multiple routes may match the same URL, the order of definition determines the match result. FastAPI matches routes in the order they are defined, and the first matching route is 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 information"""
return
{
"user_id"
:
"the current user"
}
@
app.
get
(
"/users/{user_id}"
)
async
def
read_user
(
user_id:
str
)
:
"""Get user information by ID"""
return
{
"user_id"
: user_id
}
If you place /users/me Place in the /users/{user_id} after, then when accessing /users/me , FastAPI will treat "me" Is user_id as the value, thus matching the wrong function.
Routes with fixed paths must be placed before routes with dynamic path parameters; otherwise the dynamic parameters will "swallow" the fixed path's value.
Path parameters with preset values (Enum)
When you need to restrict 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 the enum class:
| Key Points | Description |
|---|---|
inheritance str |
Let the API docs recognize the value type as a string, ensuring correct rendering |
inheritance Enum |
Create an enum type to restrict the allowed values |
model_name.value |
Get the actual value of an enum member (such as "alexnet") |
Access the http://127.0.0.1:8000/models/alexnet, returns:
{"model_name": "alexnet", "message": "Deep Learning FTW!"}
If a non-preset value is passed (such as /models/foobar), FastAPI returns a validation error indicating the allowed values are alexnet、resnet、lenet。
Path parameters containing a path
When you need a path parameter to itself contain a path (such as a file path), use Starlette's path converter:
Example
from
fastapi
import
FastAPI
app
=
FastAPI
(
)
:path indicates that the parameter can match a path containing slashes
@
app.
get
(
"/files/{file_path:path}"
)
async
def
read_file
(
file_path:
str
)
:
return
{
"file_path"
: file_path
}
Access the http://127.0.0.1:8000/files/home/johndoe/myfile.txt, returns:
{"file_path": "home/johndoe/myfile.txt"}
Note that in the URL
/files/and/home/a double slash appears between//, which is normal because the path parameter starts with/at the beginning.
Summary
Through standard Python type declarations, FastAPI path parameters gain:
- Data Transformation: the string in the URL is automatically converted to the declared type
- Data validation: clear error messages are returned when types do not match
- Automatic documentation: path parameter types and constraints automatically appear in the API docs
- Editor support: type annotations give you autocompletion in the editor