为什么是 FastAPI

类型提示即文档,自动生成交互式 API 文档,对写过前端 TS 的人非常友好。

第一个接口

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def hello(name: str = "world"):
    return {"message": f"hello {name}"}

数据校验:Pydantic 一把梭

from pydantic import BaseModel

class Moment(BaseModel):
    content: str
    mood: str | None = None

请求体不对直接 422,错误信息清晰,不用手写校验。

感想

写惯了 JS 的我,第一次觉得 Python 的类型提示真香。后续博客的本地管理后台,就用它来写。