
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 appFastAPI()classItem(BaseModel):name:strprice:floatis_offer:boolFalseapp.get(/items/{item_id})defread_item(item_id:int,q:strNone):return{item_id:item_id,q:q}app.post(/items/)defcreate_item(item:Item):returnitem2.2 自动交互式 API 文档启动应用后访问/docsSwagger UI或/redocReDoc即可获得完整的交互式 API 文档。文档基于 OpenAPI 标准自动生成并支持直接在浏览器中测试 API 端点。2.3 数据验证与序列化通过 Pydantic 模型FastAPI 自动验证请求数据并在数据无效时返回清晰的错误信息。同时它还能自动将响应数据序列化为 JSON。2.4 依赖注入系统FastAPI 内置了一个强大且易于使用的依赖注入系统可以轻松管理共享逻辑如数据库连接、认证、权限检查等并保持代码的整洁和可测试性。fromfastapiimportDepends,FastAPI appFastAPI()defcommon_parameters(q:strNone,skip:int0,limit:int100):return{q:q,skip:skip,limit:limit}app.get(/items/)defread_items(commons:dictDepends(common_parameters)):returncommons2.5 异步支持FastAPI 完全支持async和await可以轻松编写异步端点高效处理 I/O 密集型操作如数据库查询、外部 API 调用。fromfastapiimportFastAPIimportasyncio appFastAPI()app.get(/)asyncdefread_root():awaitasyncio.sleep(1)# 模拟异步操作return{Hello:World}3. 快速入门3.1 安装pipinstallfastapi pipinstalluvicorn[standard]# ASGI 服务器用于运行应用3.2 创建第一个应用创建一个名为main.py的文件fromfastapiimportFastAPI appFastAPI()app.get(/)defread_root():return{Hello:World}app.get(/items/{item_id})defread_item(item_id:int,q:strNone):return{item_id:item_id,q:q}3.3 运行应用使用 Uvicorn 运行应用uvicorn main:app--reloadmainPython 模块名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 appFastAPI()classItem(BaseModel):name:strdescription:Optional[str]Noneprice:floattax:Optional[float]Noneapp.post(/items/)defcreate_item(item:Item):item_dictitem.dict()ifitem.tax:price_with_taxitem.priceitem.tax item_dict.update({price_with_tax:price_with_tax})returnitem_dict4.2 路径参数与查询参数路径参数作为 URL 路径的一部分如/items/{item_id}通过函数参数类型提示自动转换和验证。查询参数作为 URL 问号后的键值对如?qsearch可设置默认值、可选性等。4.3 响应模型使用response_model参数声明响应的数据结构FastAPI 会自动过滤和序列化返回的数据。fromfastapiimportFastAPIfrompydanticimportBaseModel appFastAPI()classUserIn(BaseModel):username:strpassword:stremail:strclassUserOut(BaseModel):username:stremail:strapp.post(/user/,response_modelUserOut)defcreate_user(user:UserIn):# 密码不会出现在响应中returnuser4.4 错误处理FastAPI 提供了HTTPException用于返回自定义 HTTP 错误。fromfastapiimportFastAPI,HTTPException appFastAPI()items{foo:The Foo Wrestlers}app.get(/items/{item_id})defread_item(item_id:str):ifitem_idnotinitems:raiseHTTPException(status_code404,detailItem not found)return{item:items[item_id]}4.5 中间件可以添加中间件来处理请求和响应例如添加 CORS 头、记录请求日志等。fromfastapiimportFastAPIfromfastapi.middleware.corsimportCORSMiddleware appFastAPI()app.add_middleware(CORSMiddleware,allow_origins[*],# 生产环境应指定具体域名allow_credentialsTrue,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:strMy FastAPI Appadmin_email:stritems_per_user:int50classConfig:env_file.envsettingsSettings()5.3 数据库集成FastAPI 不绑定任何特定的数据库可以自由选择。常见组合有SQL关系型SQLAlchemy Alembic迁移NoSQLMongoDBMotor、Redisaioredis异步 ORMTortoise-ORM、SQLModel