FastAPI入门:响应模型
响应模型
在任意的路径操作中使用 response_model 参数来声明用于响应的模型
FastAPI 将使用此 response_model 来:
- 将输出数据限制在该模型定义内
- 将输出数据转换为其声明的类型。
- 校验数据。
- 在 OpenAPI 的路径操作中为响应添加一个 JSON Schema。
- 并在自动生成文档系统中使用。
返回与输入相同的模型
from typing import Anyfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = Nonetags: list[str] = []@app.post("/items/", response_model=Item)
async def create_item(item: Item) -> Any:return item@app.get("/items/", response_model=list[Item])
async def read_items() -> Any:return [Item(name="Item 1", description="A sample item", price=10.0, tax=1.0, tags=["tag1", "tag2"]),Item(name="Item 2", description="Another sample item", price=20.0, tax=2.0, tags=["tag3"]),]
添加输出模型
from typing import Anyfrom fastapi import FastAPI
from pydantic import BaseModel, EmailStrapp = FastAPI()class UserInput(BaseModel):username: strpassword: stremail: EmailStr fullname: str | None = Noneclass UserOutput(BaseModel):username: stremail: EmailStrfullname: str | None = None@app.post("/user/", response_model=UserOutput)
async def create_user(user: UserInput) -> Any:return user
将 response_model 声明为了不包含密码的 UserOut 模型
response_model_exclude_unset
设置response_model_exclude_unset=True响应中将不会包含那些默认值,而是仅有实际设置的值。
from typing import List, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: float = 10.5tags: List[str] = []items = {"foo": {"name": "Foo", "price": 50.2},"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}@app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
async def read_item(item_id: str):return items[item_id]
访问http://127.0.0.1:8000/items/foo,将只显示
response_model_include 和 response_model_exclude
使用路径操作装饰器的 response_model_include 和 response_model_exclude 参数。
它们接收一个由属性名称 str 组成的 set 来包含(忽略其他的)或者排除(包含其他的)这些属性。
from typing import List, Unionfrom fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: float = 10.5tags: List[str] = []items = {"foo": {"name": "Foo", "price": 50.2},"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}@app.get("/items/{item_id}/name",response_model=Item,response_model_include={"name", "description"},)
async def read_item(item_id: str):return items[item_id]@app.get("/items/{item_id}/public", response_model=Item,response_model_exclude={"tax"})
async def read_item(item_id: str):return items[item_id]
访问:http://127.0.0.1:8000/items/foo/public
访问http://127.0.0.1:8000/items/foo/name: