FastAPI path parameters

Path parameters are the dynamic parts of the URL path, using curly braces to{}declare. FastAPI automatically passes path parameters to the path operation function, and performs data conversion and validation based on type annotations.


Basic Usage

Use Python formatted string syntax to declare path parameters:

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}

Visithttp://127.0.0.1:8000/items/5, returns:

{"item_id": 5}

Note the returneditem_idis an integer5, not a string"5". FastAPI, using type annotations,item_id: intautomatically converts the string in the URL to an integer.


Data conversion

When you declare the type asintWhen , FastAPI automatically performs type conversion:

# 传入整数,正常工作
GET /items/3       -> {"item_id": 3}

# 传入非整数,返回校验错误
GET /items/foo     -> 错误:Input should be a valid integer

# 传入浮点数,同样报错
GET /items/4.2     -> 错误:Input should be a valid integer

Visithttp://127.0.0.1:8000/items/fooWhen , the validation error information 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 and will point out the exact error location (loc), error type (type) and error description (msg). This is very useful when debugging.


The type of the path parameter

exceptint, you can also use other standard Python types:

TypeDescriptionURL Example
strString (default type)/items/foo
intInteger/items/5
floatFloating-point number/items/5.5
boolBoolean value/items/true
uuid.UUIDUUID/items/3fa85f64-5717-4562-b3fc-2c963f66afa6

Path order matters

When multiple routes may match the same URL, the order of definition determines the matching result. FastAPI matches routes one by one 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 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 put/users/mePlace/users/{user_id}After that, then access/users/meFastAPI will consider"me"Yesuser_idthe value, thereby matching the wrong function.

Routes with fixed paths must be placed before routes with dynamic path parameters, otherwise the dynamic parameters will "swallow" the value of the fixed path.


Path parameters with preset values (Enum)

When you need to restrict a path parameter to several fixed values, you can use Python'sEnumType:

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:

Key pointsDescription
Inheritancestrto make the API documentation recognize the value type as a string, ensuring correct rendering
InheritanceEnumCreate an Enum type to limit the selectable values.
model_name.valueGet the actual value of the enum member (e.g."alexnet")

Visithttp://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 allowed values arealexnet、resnet、lenet。


Path parameters containing a path

When you need the path parameter itself to contain a path (such as 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}

Visithttp://127.0.0.1:8000/files/home/johndoe/myfile.txt, returns:

{"file_path": "home/johndoe/myfile.txt"}

Note in the URL/files/and/home/double slashes will appear between//This is normal, because path parameters begin with/beginning.


Summary

Through Python standard type declarations, FastAPI path parameters can simultaneously obtain:

  • Data conversion: The string in the URL is automatically converted to the declared type
  • Data verification: When the type does not match, clear error information is returned
  • Automatic documentation: The types and constraints of path parameters automatically appear in the API documentation
  • Editor support: Type annotations provide autocompletion in the editor
other extensions