FastAPIルーティング完全ガイド
FastAPIルーティング完全ガイド
Section titled “FastAPIルーティング完全ガイド”FastAPIのルーティング機能を、実務で使える実装例とともに詳しく解説します。
1. ルーティングとは
Section titled “1. ルーティングとは”ルーティングの役割
Section titled “ルーティングの役割”ルーティングは、HTTPリクエストを適切なエンドポイント関数に振り分ける仕組みです。
リクエスト ↓(ルーティング)適切なエンドポイント関数 ↓レスポンスなぜルーティングが必要か
Section titled “なぜルーティングが必要か”問題のある構成(ルーティングなし):
# 問題: すべてのエンドポイントを1つのファイルに記述from fastapi import FastAPI
app = FastAPI()
@app.get("/users/")def get_users(): pass
@app.get("/items/")def get_items(): pass
@app.get("/orders/")def get_orders(): pass
# 問題点:# 1. ファイルが肥大化# 2. 保守性が低い# 3. チーム開発が困難解決: ルーターによる分割
# 解決: ルーターで分割from fastapi import APIRouter
router = APIRouter()
@router.get("/users/")def get_users(): pass
# メインファイルで統合app.include_router(router, prefix="/api/v1")2. 基本的なルーティング
Section titled “2. 基本的なルーティング”HTTPメソッドの定義
Section titled “HTTPメソッドの定義”from fastapi import FastAPI
app = FastAPI()
# GETメソッド@app.get("/items/")def get_items(): return {"items": []}
# POSTメソッド@app.post("/items/")def create_item(): return {"message": "Item created"}
# PUTメソッド@app.put("/items/{item_id}")def update_item(item_id: int): return {"item_id": item_id}
# DELETEメソッド@app.delete("/items/{item_id}")def delete_item(item_id: int): return {"message": "Item deleted"}パスパラメータ
Section titled “パスパラメータ”@app.get("/items/{item_id}")def read_item(item_id: int): return {"item_id": item_id}
# 複数のパスパラメータ@app.get("/users/{user_id}/items/{item_id}")def read_user_item(user_id: int, item_id: int): return {"user_id": user_id, "item_id": item_id}クエリパラメータ
Section titled “クエリパラメータ”from typing import Optional
@app.get("/items/")def read_items(skip: int = 0, limit: int = 100, q: Optional[str] = None): return {"skip": skip, "limit": limit, "q": q}3. APIRouterの使用
Section titled “3. APIRouterの使用”基本的なルーター
Section titled “基本的なルーター”from fastapi import APIRouter
router = APIRouter()
@router.get("/users/")def get_users(): return {"users": []}
@router.post("/users/")def create_user(): return {"message": "User created"}メインアプリケーションでの統合
Section titled “メインアプリケーションでの統合”from fastapi import FastAPIfrom app.api.v1.endpoints import users
app = FastAPI()
app.include_router(users.router, prefix="/api/v1", tags=["users"])4. ルーターの階層化
Section titled “4. ルーターの階層化”バージョン管理
Section titled “バージョン管理”from fastapi import APIRouterfrom app.api.v1.endpoints import users, items
api_router = APIRouter()
api_router.include_router(users.router, prefix="/users", tags=["users"])api_router.include_router(items.router, prefix="/items", tags=["items"])
# app/main.pyfrom app.api.v1 import api_router
app.include_router(api_router, prefix="/api/v1")5. ルートの設定
Section titled “5. ルートの設定”レスポンスモデルの指定
Section titled “レスポンスモデルの指定”from pydantic import BaseModel
class ItemResponse(BaseModel): id: int name: str price: float
@app.get("/items/{item_id}", response_model=ItemResponse)def get_item(item_id: int): return {"id": item_id, "name": "Item", "price": 100.0}ステータスコードの指定
Section titled “ステータスコードの指定”from fastapi import status
@app.post("/items/", status_code=status.HTTP_201_CREATED)def create_item(): return {"message": "Item created"}タグとサマリー
Section titled “タグとサマリー”@app.get( "/items/", tags=["items"], summary="アイテム一覧の取得", description="すべてのアイテムを取得します", response_description="アイテムのリスト")def get_items(): return {"items": []}6. 実務でのベストプラクティス
Section titled “6. 実務でのベストプラクティス”パターン1: ルーターの構造化
Section titled “パターン1: ルーターの構造化”app/├── api/│ ├── __init__.py│ └── v1/│ ├── __init__.py│ └── endpoints/│ ├── __init__.py│ ├── users.py│ ├── items.py│ └── orders.py└── main.pyfrom fastapi import APIRouterfrom app.api.v1.endpoints import users, items, orders
api_router = APIRouter()
api_router.include_router(users.router, prefix="/users", tags=["users"])api_router.include_router(items.router, prefix="/items", tags=["items"])api_router.include_router(orders.router, prefix="/orders", tags=["orders"])パターン2: 共通の依存性
Section titled “パターン2: 共通の依存性”from fastapi import Dependsfrom sqlalchemy.orm import Sessionfrom app.database import get_db
def get_current_user(db: Session = Depends(get_db)): # 認証ロジック pass
# app/api/v1/endpoints/users.pyfrom app.api.dependencies import get_current_user
@router.get("/users/me")def get_current_user_info(current_user: str = Depends(get_current_user)): return {"user": current_user}7. よくある問題と解決策
Section titled “7. よくある問題と解決策”問題1: ルートがマッチしない
Section titled “問題1: ルートがマッチしない”原因:
- ルートの順序が間違っている
- パスパラメータの型が間違っている
解決策:
# より具体的なルートを先に定義@app.get("/users/me")def get_current_user(): pass
@app.get("/users/{user_id}")def get_user(user_id: int): pass問題2: ルーターが読み込まれない
Section titled “問題2: ルーターが読み込まれない”原因:
include_routerが実行されていない- パスが間違っている
解決策:
# メインファイルでルーターを確実に読み込むfrom app.api.v1 import api_router
app.include_router(api_router, prefix="/api/v1")これで、FastAPIのルーティングの基礎知識と実務での使い方を理解できるようになりました。