1. 引言
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于基于标准 Python 类型提示构建 API。它由 Sebastián Ramírez 于 2018 年创建,并迅速成为 Python 社区中最受欢迎的 Web 框架之一。FastAPI 的设计理念是让开发者能够以最少的代码、最快的速度构建高性能的 API,同时提供自动生成的交互式文档、数据验证、序列化等开箱即用的功能。
1.1 为什么选择 FastAPI?
- 极致的性能:基于 Starlette(用于 Web 微服务)和 Pydantic(用于数据验证),性能可与 Node.js 和 Go 相媲美。
- 快速开发:通过 Python 类型提示自动生成 API 文档(Swagger UI 和 ReDoc),减少大量手动编写文档的时间。
- 易于学习:如果你熟悉 Python,特别是类型提示,那么上手 FastAPI 将非常容易。
- 生产就绪:支持异步请求、WebSocket、GraphQL、OAuth2、JWT 等现代 Web 开发所需的功能。
- 强大的生态系统:与 SQLAlchemy、Tortoise-ORM、Databases 等流行库无缝集成。
2. 核心特性
2.1 基于 Python 类型提示
FastAPI 充分利用 Python 3.6+ 的类型提示功能,自动处理数据验证、序列化和文档生成。你只需声明参数的类型,框架就会自动完成其余工作。
fromfastapiimportFastAPIfrompydanticimportBaseModel app=FastAPI()classItem(BaseModel):name:strprice:floatis_offer:bool=False@app.get("/items/{item_id}")defread_item(item_id:int,q:str=None):return{"item_id":item_id,"q":q}@app.post("/items/")defcreate_item(item:Item):returnitem2.2 自动交互式 API 文档
启动应用后,访问/docs(Swagger UI)或/redoc(ReDoc)即可获得完整的交互式 API 文档。文档基于 OpenAPI 标准自动生成,并支持直接在浏览器中测试 API 端点。
2.3 数据验证与序列化
通过 Pydantic 模型,FastAPI 自动验证请求数据,并在数据无效时返回清晰的错误信息。同时,它还能自动将响应数据序列化为 JSON。
2.4 依赖注入系统
FastAPI 内置了一个强大且易于使用的依赖注入系统,可以轻松管理共享逻辑(如数据库连接、认证、权限检查等),并保持代码的整洁和可测试性。
fromfastapiimportDepends,FastAPI app=FastAPI()defcommon_parameters(q:str=None,skip:int=0,limit:int=100):return{"q":q,"skip":skip,"limit":limit}@app.get("/items/")defread_items(commons:dict=Depends(common_parameters)):returncommons2.5 异步支持
FastAPI 完全支持async和await,可以轻松编写异步端点,高效处理 I/O 密集型操作(如数据库查询、外部 API 调用)。
fromfastapiimportFastAPIimportasyncio app=FastAPI()@app.get("/")asyncdefread_root():awaitasyncio.sleep(1)# 模拟异步操作return{"Hello":"World"}3. 快速入门
3.1 安装
pipinstallfastapi pipinstall"uvicorn[standard]"# ASGI 服务器,用于运行应用3.2 创建第一个应用
创建一个名为main.py的文件:
fromfastapiimportFastAPI app=FastAPI()@app.get("/")defread_root():return{"Hello":"World"}@app.get("/items/{item_id}")defread_item(item_id:int,q:str=None):return{"item_id":item_id,"q":q}3.3 运行应用
使用 Uvicorn 运行应用:
uvicorn main:app--reloadmain:Python 模块名(main.py)。app:在main.py中创建的 FastAPI 实例。--reload:开发模式下,代码更改后自动重启服务器。
访问http://127.0.0.1:8000查看响应,访问http://127.0.0.1:8000/docs查看交互式文档。
4. 进阶功能
4.1 请求体与 Pydantic 模型
使用 Pydantic 模型定义复杂请求体的结构。
fromfastapiimportFastAPIfrompydanticimportBaseModelfromtypingimportOptional app=FastAPI()classItem(BaseModel):name:strdescription:Optional[str]=Noneprice:floattax:Optional[float]=None@app.post("/items/")defcreate_item(item:Item):item_dict=item.dict()ifitem.tax:price_with_tax=item.price+item.tax item_dict.update({"price_with_tax":price_with_tax})returnitem_dict4.2 路径参数与查询参数
- 路径参数:作为 URL 路径的一部分(如
/items/{item_id}),通过函数参数类型提示自动转换和验证。 - 查询参数:作为 URL 问号后的键值对(如
?q=search),可设置默认值、可选性等。
4.3 响应模型
使用response_model参数声明响应的数据结构,FastAPI 会自动过滤和序列化返回的数据。
fromfastapiimportFastAPIfrompydanticimportBaseModel app=FastAPI()classUserIn(BaseModel):username:strpassword:stremail:strclassUserOut(BaseModel):username:stremail:str@app.post("/user/",response_model=UserOut)defcreate_user(user:UserIn):# 密码不会出现在响应中returnuser4.4 错误处理
FastAPI 提供了HTTPException用于返回自定义 HTTP 错误。
fromfastapiimportFastAPI,HTTPException app=FastAPI()items={"foo":"The Foo Wrestlers"}@app.get("/items/{item_id}")defread_item(item_id:str):ifitem_idnotinitems:raiseHTTPException(status_code=404,detail="Item not found")return{"item":items[item_id]}4.5 中间件
可以添加中间件来处理请求和响应,例如添加 CORS 头、记录请求日志等。
fromfastapiimportFastAPIfromfastapi.middleware.corsimportCORSMiddleware app=FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],# 生产环境应指定具体域名allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)5. 部署与生产
5.1 使用 Gunicorn 与 Uvicorn Workers
对于生产环境,建议使用 Gunicorn 作为进程管理器,配合 Uvicorn Workers。
pipinstallgunicorn gunicorn-w4-kuvicorn.workers.UvicornWorker main:app5.2 环境变量与配置
使用 Pydantic 的BaseSettings管理配置。
frompydanticimportBaseSettingsclassSettings(BaseSettings):app_name:str="My FastAPI App"admin_email:stritems_per_user:int=50classConfig:env_file=".env"settings=Settings()5.3 数据库集成
FastAPI 不绑定任何特定的数据库,可以自由选择。常见组合有:
- SQL(关系型):SQLAlchemy + Alembic(迁移)
- NoSQL:MongoDB(Motor)、Redis(aioredis)
- 异步 ORM:Tortoise-ORM、SQLModel