FastAPI入門:Pythonで高速APIサーバーを構築する方法
FastAPIの基本から実践まで。Pythonで高速なAPIサーバーを構築する方法を解説。非同期処理、Pydantic、Swagger UIの自動生成、デプロイまでカバーします。
FastAPIとは?
FastAPIは、PythonでAPIサーバーを構築するためのモダンなWebフレームワークです。高速なパフォーマンスと直感的な開発体験が特徴で、以下のようなメリットがあります。
環境構築
まずはPython 3.7以上が必要です。仮想環境を作成し、FastAPIとUvicorn(ASGIサーバー)をインストールします。
<h1>仮想環境の作成(任意)</h1>
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
<h1>必要なパッケージのインストール</h1>
pip install fastapi uvicorn
最小限のAPIサーバー
main.pyを作成し、以下のコードを記述します。
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
サーバーを起動します。
uvicorn main:app --reload
ブラウザで http://127.0.0.1:8000 にアクセスすると、{"Hello":"World"} が表示されます。また、http://127.0.0.1:8000/docs でSwagger UIによるAPIドキュメントが自動生成されていることを確認できます。
パスパラメータとクエリパラメータ
パスパラメータはURLの一部として、クエリパラメータは?key=value形式で渡します。
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
item_id: パスパラメータ(int型に自動変換)q: クエリパラメータ(デフォルトはNone)Pydanticによるリクエストボディ
POSTリクエストなどでJSONデータを受け取るには、Pydanticのモデルを定義します。
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.post("/items/")
def create_item(item: Item):
return {"name": item.name, "price": item.price}
FastAPIが自動でバリデーションを行い、不正なデータは400エラーを返します。
非同期エンドポイント
FastAPIは非同期処理をネイティブサポートしています。async defを使うことで、I/Oバウンドな処理を効率的に行えます。
@app.get("/async-example")
async def async_endpoint():
# 非同期処理(例: データベースクエリ)
await some_async_function()
return {"message": "Async response"}
同期関数と非同期関数は共存可能で、FastAPIが適切に処理します。
依存性注入(Dependency Injection)
共通の処理(認証、データベース接続など)を依存性として注入できます。
from fastapi import Depends
def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
def read_items(commons: dict = Depends(common_parameters)):
return commons
エラーハンドリング
HTTPExceptionを使って適切なステータスコードを返します。
from fastapi import HTTPException
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return items[item_id]
自動ドキュメントのカスタマイズ
Swagger UIやReDocの見た目をカスタマイズできます。
app = FastAPI(title="My API", description="サンプルAPI", version="1.0.0")
デプロイ
本番環境では、UvicornをGunicornと組み合わせて使うことが推奨されます。
pip install gunicorn
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
また、Dockerを使うと簡単にコンテナ化できます。
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
まとめ
FastAPIは、高速で型安全、自動ドキュメント生成など、現代的なAPI開発に必要な機能を備えています。非同期処理にも対応しており、小規模から大規模まで幅広く活用できます。ぜひ実際にコードを書いて、その開発体験を体感してください。
参考リンク: