推荐答案
在 FastAPI 中,类型提示用于定义请求参数、响应模型以及函数参数和返回值的类型。FastAPI 利用这些类型提示来自动生成 API 文档、进行数据验证和序列化。
1. 请求参数的类型提示
在 FastAPI 中,路径参数、查询参数、请求体等都可以使用类型提示来定义其类型。
// www.javascriptcn.com code example
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.get("/items/{item_id}")
async def read_item(
item_id: int = Path(..., title="The ID of the item to get"),
q: str | None = Query(None, alias="item-query"),
):
return {"item_id": item_id, "q": q}
@app.post("/items/")
async def create_item(item: Item):
return item2. 响应模型的类型提示
FastAPI 允许你使用类型提示来定义响应模型,以确保返回的数据符合预期的结构。
from typing import List
@app.get("/items/", response_model=List[Item])
async def read_items():
return [
Item(name="Foo", price=42.0),
Item(name="Bar", price=32.0),
]3. 函数参数和返回值的类型提示
FastAPI 支持在函数参数和返回值中使用类型提示,以便更好地进行代码检查和文档生成。
@app.get("/items/{item_id}")
async def read_item(item_id: int) -> Item:
return Item(name="Foo", price=42.0)本题详细解读
1. 类型提示的作用
类型提示在 FastAPI 中有以下几个主要作用:
- 数据验证:FastAPI 会根据类型提示自动验证请求数据,确保传入的数据符合预期的类型。
- 自动文档生成:FastAPI 会根据类型提示自动生成 API 文档,包括请求参数、响应模型等信息。
- 代码可读性:类型提示可以提高代码的可读性,使开发者更容易理解函数的输入和输出。
2. 类型提示的类型
FastAPI 支持多种类型提示,包括:
- 基本类型:如
int,str,float,bool等。 - 复合类型:如
List,Dict,Set,Tuple等。 - 自定义类型:如 Pydantic 模型、枚举类型等。
3. Pydantic 模型
Pydantic 是 FastAPI 中用于数据验证和序列化的核心库。通过定义 Pydantic 模型,你可以轻松地处理复杂的请求体和响应数据。
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str4. 可选类型和默认值
在类型提示中,你可以使用 Optional 或 | None 来表示可选参数,并为它们设置默认值。
from typing import Optional
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}5. 响应模型
通过 response_model 参数,你可以指定视图函数的返回类型,FastAPI 会自动将返回值转换为指定的模型。
@app.get("/users/{user_id}", response_model=User)
async def read_user(user_id: int):
return User(id=user_id, name="John Doe", email="john@example.com")6. 嵌套模型
FastAPI 支持嵌套的 Pydantic 模型,允许你处理复杂的数据结构。
// www.javascriptcn.com code example
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
class Order(BaseModel):
user: User
items: List[Item]
@app.post("/orders/")
async def create_order(order: Order):
return order通过以上方式,你可以在 FastAPI 中充分利用类型提示来增强代码的健壮性和可读性。