跳转至

理解代码

本页阅读生成应用中 shop 项目的 main.py,并向每个端点发送正确和错误的请求。你将了解 FastAPI 如何读取查询参数、路径参数和 JSON 请求体,如何校验它们并在值有误时返回 422,响应模型和状态码如何决定返回的内容,HTTPException 如何返回错误,以及什么时候应该写 async def。

如何阅读 main.py

请从上到下阅读 main.py。文件第一次用到某个 FastAPI 概念时,会有一到两行注释解释它,注释末尾附有讲解该概念的 FastAPI 教程页面链接。每个概念只注释一次,所以后面做同样事情的端点就不再带注释。

如果想边读边动手,请在项目文件夹中用 fastkit runserver 启动服务器,然后在第二个终端中发送下面的请求。条目保存在内存中,所以如果你已经在 /docs 中创建过条目,请先重启服务器;如果不重启,你得到的 id 会与下面的不同,这时请使用你的 POST 请求返回的 id。你也可以在 http://127.0.0.1:8000/docs 中通过“Try it out”发送同样的请求。

应用和模型

pydantic 模型是一个类,它的属性声明了 JSON 对象的字段及其类型。FastAPI 用它来读取请求体、检查请求体,并把它转换成 Python 对象。Field(...) 用于添加限制:这里要求名称为 1 到 100 个字符,价格大于 0。

main.py
app = FastAPI(title="shop")


# An argument typed with a pydantic model (`item: Item`) is the validated JSON body.
# https://fastapi.tiangolo.com/tutorial/body/
class Item(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    price: float = Field(gt=0)
    description: str | None = None


# The return type of an endpoint is its response model: it shapes the output.
# https://fastapi.tiangolo.com/tutorial/response-model/
class StoredItem(Item):
    id: int


items: dict[int, StoredItem] = {}

StoredItem 就是多了一个 id 的 Item:客户端发送 Item,API 返回 StoredItem。items 是一个普通的字典,把条目保存在内存中,因此服务器重启后这些条目就没有了。

查询参数

查询参数是 URL 中 ? 后面的 key=value 键值对,例如 /?name=Ada。在 FastAPI 中,类型为 str 或 int 这类简单类型、又不属于路径的参数,默认就是查询参数;而类型为 pydantic 模型的参数则从请求体中读取,下一节会介绍这一点。Query(...) 用于添加限制,默认值("World")让这个参数变为可选。

main.py
@app.get("/")
async def read_root(
    # A str, int or bool argument not in the path is a query parameter: /?name=Ada
    # https://fastapi.tiangolo.com/tutorial/query-params/
    name: Annotated[str, Query(min_length=1, max_length=50)] = "World",
) -> dict[str, str]:
    return {"message": f"Hello, {name}! Welcome to {app.title}", "docs": "/docs"}

空的名称违反了 min_length=1 这条限制。FastAPI 会在你的函数运行之前拒绝这个请求,并返回 422 Unprocessable Entity。响应体会指出问题出在哪里(loc:查询参数 name)以及出了什么问题(msg):

$ curl -s -i "http://127.0.0.1:8000/?name="
HTTP/1.1 422 Unprocessable Entity
...
{"detail":[{"type":"string_too_short","loc":["query","name"],"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}}]}

请求体和状态码

如果参数的类型是 pydantic 模型,FastAPI 就会从请求的 JSON 请求体中读取它。返回类型 StoredItem 是响应模型:FastAPI 会用它检查返回的对象,只发送其中定义的字段,并在 /docs 中为它生成文档。status_code=status.HTTP_201_CREATED 把默认的 200 换成 201 Created,这是请求创建了新内容时通常使用的状态码。

main.py
# `status_code` sets the status of a successful response: 201 Created.
# https://fastapi.tiangolo.com/tutorial/response-status-code/
@app.post("/items", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item) -> StoredItem:
    stored = StoredItem(id=len(items) + 1, **item.model_dump())
    items[stored.id] = stored
    return stored
$ curl -s -i -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"name": "Hammer", "price": 9.5}'
HTTP/1.1 201 Created
...
{"name":"Hammer","price":9.5,"description":null,"id":1}

请求体中没有 description,所以它的值是模型中的默认值 null(即 Python 的 None)。负数价格违反了 Field(gt=0),422 响应体会指向请求体中的 price:

$ curl -s -i -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"name": "Saw", "price": -1}'
HTTP/1.1 422 Unprocessable Entity
...
{"detail":[{"type":"greater_than","loc":["body","price"],"msg":"Input should be greater than 0","input":-1,"ctx":{"gt":0.0}}]}

在 Swagger UI 中用请求体 {"name": "Hammer", "price": 9.5} 执行 POST /items 之后:显示 curl 命令,以及包含新条目及其 id 的 201 响应

在 Swagger UI 中以 -1 作为价格执行 POST /items 之后:422 响应的 detail 指出价格必须大于 0

路径参数和错误

路径参数是路径本身的一部分,在装饰器中写作 {item_id}。FastAPI 把它传给同名的函数参数,并转换成声明的类型 int。如果没有条目使用这个 id,函数就会抛出 HTTPException:FastAPI 会在这里中止请求,并用你指定的状态码和 detail 作为响应。

main.py
# `{item_id}` in the path arrives as an argument, converted to `int`.
# https://fastapi.tiangolo.com/tutorial/path-params/
@app.get("/items/{item_id}")
async def read_item(item_id: int) -> StoredItem:
    if item_id not in items:
        # HTTPException stops the request and answers with an error status.
        # https://fastapi.tiangolo.com/tutorial/handling-errors/
        raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Item not found")
    return items[item_id]
$ curl -s http://127.0.0.1:8000/items/1
{"name":"Hammer","price":9.5,"description":null,"id":1}
$ curl -s -i http://127.0.0.1:8000/items/99
HTTP/1.1 404 Not Found
...
{"detail":"Item not found"}
$ curl -s -i http://127.0.0.1:8000/items/abc
HTTP/1.1 422 Unprocessable Entity
...
{"detail":[{"type":"int_parsing","loc":["path","item_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"}]}

abc 不是整数,所以 FastAPI 不会调用 read_item,直接返回 422。你永远不需要自己转换或检查 item_id。

async def 还是 def

main.py 中的每个端点都是 async def 函数。在 async def 中,你可以 await 其他异步代码,例如异步数据库驱动或 HTTP 客户端;某个请求在等待时,服务器可以处理其他请求。这些端点只读写一个字典,所以从不需要等待。如果端点调用的是会阻塞的库(不支持 await 的库),请使用普通的 def:这样 FastAPI 会在线程池中运行它,它就不会拖住其他请求。

FastAPI 文档

下一步

扩展应用添加一个 /users 资源:先手动添加,再借助 layered 项目和 fastkit addroute 添加。