项目简介
FastAPI 是一个现代高性能 Python Web 框架,基于标准类型提示构建 API。通过 OpenAPI 与 JSON Schema 自动生成交互式文档,借助 Pydantic 进行数据校验,并基于 Starlette 支持异步。易于学习、开发高效,可直接用于生产环境。
README 预览
\n \n\n\n FastAPI framework, high performance, easy to learn, fast to code, ready for production\n\n\n\n \n\n\n \n\n\n \n\n\n \n\n\n\n---\n\n**Documentation**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com)\n\n**Source Code**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)\n\n---\n\nFastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.\n\nThe key features are:\n\n* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).\n* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *\n* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *\n* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.\n* **Easy**: Designed to be easy to use and learn. Less time reading docs.\n* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.\n* **Robust**: Get production-ready code. With automatic interactive documentation.\n* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (previously known as Swagger) and [JSON Schema](https://json-schema.org/).\n\n* estimation based on tests conducted by an internal development team, building production applications.\n\n## Sponsors\n\n\n### Keystone Sponsor\n\n\n\n### Gold Sponsors\n\n\n\n\n\n\n\n\n\n### Silver Sponsors\n\n\n\n\n\n\n\n\n\n[Other sponsors](https://fastapi.tiangolo.com/fastapi-people/#sponsors)\n\n## Opinions\n\n\n\n\n\n"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"\n\nKabir Khan - Microsoft (ref)\n\n---\
常见问题 (4)
故障排除为什么设置了 OTEL_EXPORTER_OTLP_ENDPOINT 会导致 FastAPI 0.142.0 无法启动,以及如何解决?
这是 FastAPI 0.142.0 中的一个 bug:如果设置了 OTEL_EXPORTER_OTLP_ENDPOINT 环境变量(在托管平台上很常见),但未安装 OpenTelemetry extra,应用会在启动时崩溃,报错 'Automatic OpenTelemetry export requires fastapi[opentelemetry]'。**修复方法:升级到 FastAPI 0.142.2 或更高版本**,该版本已解决此问题(PR #16418)。如果必须停留在 0.142.0,可采用的替代方案有:(1) 通过 pip install fastapi[opentelemetry] 或 fastapi[standard] 安装该 extra;(2) 通过向 FastAPI() 传递 telemetry={'auto_configure': False} 来禁用自动配置;或 (3) 降级到 FastAPI 0.141.0。
故障排除如何修复 FastAPI 的 generate_unique_id_function 中出现的 "Object of type 'APIRoute' has no attribute 'tags'" 类型检查器错误?
这是 FastAPI 0.137.0 中的一个类型注解回归问题(由 PR #15745 引入),其中 APIRoute 丢失了类级别的 tags 注解,因此类型检查器(ty、Pyright 严格模式)会在自定义的 generate_unique_id_function 中对 route.tags 报告 unresolved-attribute 错误——尽管该代码在运行时仍能正常工作。修复方法:升级到 FastAPI 0.137.1 或更高版本,该版本恢复了此注解(PR #15765):
pip install -U "fastapi>=0.137.1"
之后,文档中的模式即可正确通过类型检查:
from fastapi import FastAPI
from fastapi.routing import APIRoute
def custom_generate_unique_id(route: APIRoute) -> str:
return f"{route.tags[0]}-{route.name}"
app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
如果必须暂时停留在 0.137.0 版本,可以在 route.tags 所在行添加 # type: ignore[attr-defined] 注释来消除该错误,或者通过 getattr(route, "tags", []) 来访问它。
故障排除为什么在 router 被 include 之后,直接添加到 FastAPI APIRouter.routes 的路由会返回 404(而被移除的路由仍然会响应)?
FastAPI(自惰性路由器包含重写 #15745 起)会缓存每个被包含路由器解析后的路由,缓存以内部版本计数器(APIRouter._routes_version)为键。直接通过 append()、remove()、clear()、切片赋值或重新赋值来修改 router.routes 永远不会使该计数器递增,因此父路由器会继续提供陈旧的缓存列表:新路由返回 404,已删除的路由则继续以"幽灵"路由的形式响应。
解决方法:
1. 仅通过受跟踪的官方方法修改路由,这些方法会正确地使缓存失效:
# 替代 child.routes.append(APIRoute("/child2", handler, methods=["GET"]))
child.add_api_route("/child2", handler, methods=["GET"])
# 或者:child.add_route(...)、child.include_router(...)2. 如果必须直接修改
router.routes(例如用 app.router.routes = [...] 来剥离路由),请在修改后立即手动使缓存失效:child.routes.append(new_route)
child._mark_routes_changed() # 私有 API;在未来版本中可能发生变化3. 在路由器被包含之前、应用处理第一个请求之前完成所有直接修改,因为缓存仅在首次分发时构建。
一个让 .routes 能感知修改的正式修复方案正在 fastapi issue #16301 中讨论。
故障排除为什么 FastAPI 的 iter_route_contexts() 对 WebSocket 路由返回空路径?
这是 FastAPI 0.137.2+ 中一个已确认的 bug(在 0.141.1 中仍然存在):iter_route_contexts() 会把 include_router() 的前缀应用到 HTTP 路由上,但对 APIWebSocketRoute 会产出 ctx.path == "",而 ctx.route.path 只保存未加前缀的路径。目前还没有修复版本。变通方法:对 websocket 路由做特殊处理,通过在前面拼接你传给 include_router() 的前缀,自己重建完整路径。
from fastapi.routing import APIWebSocketRoute, iter_route_contexts
PREFIX = "/api/v1" # the prefix used in app.include_router(router, prefix=PREFIX)
for ctx in iter_route_contexts(app.routes):
if isinstance(ctx.route, APIWebSocketRoute) and not ctx.path:
full_path = PREFIX + ctx.route.path # e.g. /api/v1/stream/{job_id}
else:
full_path = ctx.path
如果你无法静态地得知前缀,它存储在私有的 _IncludedRouter.include_context.prefix 上,但该 API 是内部实现,可能会发生变化,所以在修复发布之前,自己跟踪 include_router() 的前缀是更安全的做法。