Before diving into FastAPI parameters, let’s briefly introduce FastAPI. FastAPI is a high-performance, easy-to-use Python Web framework that supports automatic API documentation generation, excellent support for parameter types, data validation, and more. When developing API interfaces, parameter handling is a core part, with common parameter types including path parameters, query parameters, and request bodies. This article will detail these three parameter types to help beginners quickly master their usage.
I. Path Parameters¶
Path parameters are parts of the URL path that act as parameters directly. For example, when accessing /items/42, 42 is the path parameter, used to identify a specific resource (e.g., a product with ID 42).
Defining Path Parameters¶
In FastAPI, define path parameters using {parameter_name} in the interface path, then declare the parameter’s type in the function parameters. FastAPI automatically extracts values from the URL path and performs type checking and conversion.
Example Code:
from fastapi import FastAPI
app = FastAPI()
# Define path parameter item_id (type: int)
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id, "message": "This is the item details"}
When accessing /items/42, the interface returns {"item_id": 42, "message": "This is the item details"}. If accessing /items/abc (non-integer), FastAPI automatically returns a type error.
Key Points¶
- Format: Path parameters are wrapped with
{parameter_name}and must match the function parameter name. - Automatic Type Conversion: FastAPI automatically converts string parameters in the URL to the declared type (e.g.,
intconverts a string to an integer). - Multiple Path Parameters: Support for multiple path parameters, e.g.,
/users/{user_id}/orders/{order_id}:
@app.get("/users/{user_id}/orders/{order_id}")
def read_user_order(user_id: int, order_id: int):
return {"user_id": user_id, "order_id": order_id}
II. Query Parameters¶
Query parameters are passed in the form of key=value after the URL question mark ?, commonly used for filtering, pagination, etc. (e.g., item_id and q in /items/?item_id=42&q=test).
Defining Query Parameters¶
Query parameters are defined similarly to regular function parameters. Simply declare them in the interface function, and FastAPI automatically extracts values from the URL query string.
Example Code:
from fastapi import FastAPI
app = FastAPI()
# Define optional query parameters (with default value None)
@app.get("/items/")
def read_items(item_id: int = None, q: str = None):
return {"item_id": item_id, "q": q}
- Accessing
/items/?item_id=42&q=testreturns{"item_id": 42, "q": "test"}. - Parameters without default values (e.g.,
item_id: int) must be passed in the URL, otherwise an error is returned.
Key Points¶
- Default Values and Optionality: Setting a default value (e.g.,
item_id: int = None) makes the parameter optional; parameters without defaults are required. - Automatic Type Recognition: FastAPI automatically converts parameters based on their declared type (e.g.,
intconverts a string to an integer; failure results in an error). - List Query Parameters: Support for list formats (e.g.,
/items/?tags=python&tags=fastapi), which FastAPI automatically parses into a list["python", "fastapi"].
III. Request Body¶
Request bodies are complex data passed via the request body (not the URL) in POST, PUT, etc. requests, typically sent in JSON format. They are suitable for passing multi-field data (e.g., name, price, description when creating a product).
In FastAPI, request bodies require Pydantic models to define data structures, which FastAPI uses to automatically parse and validate data.
Defining Request Bodies¶
- Import Pydantic Model:
from pydantic import BaseModel - Define the Model: Inherit
BaseModeland declare fields. - Use the Model as a Parameter in the Interface Function: FastAPI automatically parses and validates the request body.
Example Code:
from fastapi import FastAPI
from pydantic import BaseModel # Import Pydantic base model
app = FastAPI()
# Define request body model (product structure)
class Item(BaseModel):
name: str
price: float
description: str = None # Optional field with default None
# Use the model to receive the request body
@app.post("/items/")
def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}
Send a POST request to /items/ with the request body:
{
"name": "Python Book",
"price": 29.99,
"description": "A Python programming book"
}
FastAPI automatically parses this into an Item object and validates field types (e.g., price must be a float).
Key Points¶
- Data Validation: Pydantic models automatically validate data types and formats; errors return
422 Validation Error. - Nested Models: Support for complex structures (e.g., nested objects):
class User(BaseModel):
name: str
address: dict # Nested dictionary
- Use Cases: Complex data transfer (e.g., creating/updating resources), with clear and extensible structures.
IV. Comparison of Parameter Usage Scenarios¶
| Parameter Type | Applicable Scenarios | Transmission Method | Example |
|---|---|---|---|
| Path Parameters | Resource unique identification (e.g., ID) | URL Path | /items/{item_id} |
| Query Parameters | Filtering, pagination, optional conditions | After URL question mark (?) |
/items/?page=1&size=10 |
| Request Body | Complex data (e.g., creating resources) | Request Body (JSON) | POST /items/ (with JSON) |
V. Common Issues and Notes¶
- Parameter Order: Path parameters > Query parameters > Request body. No explicit ordering required (FastAPI automatically identifies).
- Required vs. Optional: Parameters without default values (e.g.,
item_id: int) must be passed; those with defaults (e.g.,q: str = None) are optional. - Automatic Error Handling: Type errors, missing parameters, etc., automatically return
422 Validation Error; no manual handling needed.
Mastering these three parameter types allows you to build basic and fully functional API interfaces. For further debugging and optimization, leverage FastAPI’s automatic documentation (access via /docs or /redoc).