OpenSource-Hub

fastapi

フレームワーク

fastapi/fastapi

型ヒントに基づく高性能 Python API フレームワーク。

概要

FastAPI は、標準の型ヒントに基づいて API を構築する、モダンで高性能な Python Web フレームワークです。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---\

FAQ (4)

トラブル対応
OTEL_EXPORTER_OTLP_ENDPOINT が設定されていると FastAPI 0.142.0 の起動が失敗するのはなぜですか?また、どのように修正すればよいですか?

これは FastAPI 0.142.0 のバグです。OTEL_EXPORTER_OTLP_ENDPOINT 環境変数が設定されている(ホスティングプラットフォームでは一般的)にもかかわらず、OpenTelemetry エクストラがインストールされていない場合、アプリは起動時に「Automatic OpenTelemetry export requires fastapi[opentelemetry]」というエラーでクラッシュします。**修正方法: FastAPI 0.142.2 以降にアップグレードしてください**。これによりこの問題が解決されます(PR #16418)。0.142.0 を使い続けなければならない場合の代替的な回避策: (1) pip install fastapi[opentelemetry] または fastapi[standard] でエクストラをインストールする、(2) FastAPI() に telemetry={'auto_configure': False} を渡して自動設定を無効にする、(3) FastAPI 0.141.0 にダウングレードする。

参照 Issue #16417
トラブル対応
FastAPI の generate_unique_id_function で "Object of type 'APIRoute' has no attribute 'tags'" という型チェッカーエラーを修正するには?

これは FastAPI 0.137.0 における型アノテーションのリグレッションで(PR #15745 で導入されたもの)、APIRoute がクラスレベルの tags アノテーションを失ったため、型チェッカー(ty、Pyright strict)がカスタム 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", []) 経由でアクセスしてください。

参照 Issue #15764
トラブル対応
ルーターが 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で議論されています。

参照 Issue #16301
トラブル対応
なぜFastAPIのiter_route_contexts()はWebSocketルートに対して空のパスを返すのですか?

これは FastAPI 0.137.2 以降で確認されたバグです(0.141.1 でも依然として存在します): iter_route_contexts() は HTTP ルートには include_router() のプレフィックスを適用しますが、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() のプレフィックスを自分で追跡しておく方が安全な選択肢です。

参照 Issue #16244