🧱|Spring Boot 開発者が FastAPI をレイヤード設計に分割して DI と例外ハンドリングを整理した話

python springboot fastapi pytest

前回の記事では、1 ファイルに実装したドキュメント管理 API に対して pytest と TestClient で 27 ケースの自動テストを書きました。今回はそのテストで動作を確かめながら、これまで 1 ファイルにまとめていた src/practice/main.py をレイヤード設計へ分割しました。

あわせて、初期実装から持ち越していた関数名と OpenAPI の operationId の不揃いや、作成時と更新時のバリデーション重複も整理しています。エンドポイントごとに散らばっていた 404 の例外処理も 1 箇所にまとめました。Python 固有のクラス構文や型定義には慣れが要る一方、レイヤー分割や DI の考え方自体は Spring Boot と近くイメージしやすいと感じました。

分割後の構成と Spring Boot との対応

分割後の src/practice/ 配下は次の構成です。

src/practice/
├── __init__.py
├── dependencies.py
├── exceptions.py
├── main.py
├── repositories/
│   ├── __init__.py
│   └── document.py
├── routers/
│   ├── __init__.py
│   └── documents.py
├── schemas/
│   ├── __init__.py
│   └── document.py
└── services/
    ├── __init__.py
    └── document.py

各モジュールの役割を Spring Boot の構成と並べると、おおよそ次のように対応します。

役割 Spring Boot 今回の FastAPI 構成
HTTP エンドポイント @RestController APIRouter(routers/documents.py)
ビジネスロジック @Service DocumentService(services/document.py)
データアクセス抽象 Repository インターフェース DocumentRepository(Protocol)(repositories/document.py)
依存の組み立て DI コンテナ dependencies.py と Depends
例外の HTTP 変換 @ExceptionHandler / @ControllerAdvice @app.exception_handler(main.py)
入出力の型と検証 DTO + Bean Validation Pydantic の BaseModel(schemas/document.py)

サブディレクトリごとに置いている __init__.py は、そのディレクトリが Python のパッケージであることを示すファイルです。初回 import 時に一度だけ実行される仕組みですが、副作用を避けるため今回は空のまま置いています。

また、Spring Boot では @RestController を付けるとコンポーネントスキャンで自動登録されます。FastAPI には自動スキャンがないため、分割したルーターは main.py で明示的に登録します。

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

from practice.exceptions import DocumentNotFoundError
from practice.routers.documents import router as documents_router

app = FastAPI(title="AI Knowledge Hub")


@app.exception_handler(DocumentNotFoundError)
def handle_document_not_found(
    request: Request, exc: DocumentNotFoundError
) -> JSONResponse:
    return JSONResponse(status_code=404, content={"detail": "Document not found"})


@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}


app.include_router(documents_router)

各ルーターファイルでは変数名を router に揃えておくと扱いやすくなります。main.py 側では将来エンドポイントの種類が増えたときの名前衝突を防ぐため、router as documents_router のように別名を付けて読み込みました。

Python のクラス構文と例外設計で引っかかった点

Java ではクラス内にフィールドやコンストラクタを書く形が決まっていますが、Python ではいくつか見慣れないルールに気づきました。

まず、self と __init__ です。インスタンスメソッドの第 1 引数には self を明示します。Java の this と違い、メソッド定義の引数リストから省略できません。また初期化処理は、__init__ メソッドに書きます。Java のようなクラスと同名のコンストラクタ構文は使いません。厳密にはインスタンスの生成自体は __new__ が担い、__init__ は生成直後の属性を初期化する役割です。

次に気になったのが InMemoryDocumentRepository の辞書定義です。

class InMemoryDocumentRepository:
    def __init__(self) -> None:
        self._documents: dict[UUID, DocumentResponse] = {}

Python ではクラス直下にフィールド宣言を並べなくても、__init__ 内で self._documents = ... と代入すればインスタンス属性になります。逆にクラス本体へ _documents = {} と直接書いてしまうと、Java の static フィールドのように全インスタンスで共有されるクラス変数になります。Pydantic の BaseModel はメタクラスがフィールド定義を処理するためクラス直下の記法でインスタンスごとの属性になりますが、通常のクラスでは __init__ に書く点に注意が要ります。先頭のアンダースコアはアクセス修飾子の代わりで、外部から直接参照しない内部用の属性を表す慣習です。

自作の例外クラスは src/practice/exceptions.py に切り出しました。

from uuid import UUID


class DocumentNotFoundError(Exception):
    def __init__(self, document_id: UUID) -> None:
        self.document_id = document_id
        super().__init__(f"Document not found: {document_id}")

class DocumentNotFoundError(Exception): の丸括弧は継承元クラスの指定で、Java の extends に相当します。初期化時の引数は __init__ の側へ書き、親クラスの初期化には super().__init__(...) を呼び出します。

Python には Java のような検査例外と throws 宣言がなく、例外はすべて非検査として扱われます。そのため RuntimeException のような区別はなく、業務例外やドメイン例外は Exception を継承して作ります。基底の BaseException は KeyboardInterrupt や SystemExit も含むため、通常の用途では直接継承しません。

Service 層では HTTPException を使わず DocumentNotFoundError を raise し、main.py に登録した @app.exception_handler(DocumentNotFoundError) でステータス 404 の JSON レスポンスへ変換する構成にしました。これにより Service 層が HTTP の知識を持たずに済みます。

Protocol と Depends で依存を差し替えやすくする

データアクセス層の抽象化には typing.Protocol を使いました。

class DocumentRepository(Protocol):
    def save(self, document: DocumentResponse) -> DocumentResponse: ...
    def find_by_id(self, document_id: UUID) -> DocumentResponse | None: ...
    def find_all(
        self, *, tag: str | None = None, limit: int = 20, offset: int = 0
    ) -> list[DocumentResponse]: ...
    def delete(self, document_id: UUID) -> bool: ...

Protocol は PEP 544 で定義された構造的部分型です。Java の interface と異なり implements を書かなくても、同じシグネチャのメソッドが揃っていれば型チェッカー上その型を満たすと判定されます。メソッド末尾の ... は省略記号の飾りではなく、組み込み定数 Ellipsis を表すリテラルです。Protocol では実装本体をここに書かないメソッド定義のプレースホルダとして使われます。

実装時に引っかかったのは、仮引数名の不一致でした。DocumentRepository 側を document_id にし、InMemoryDocumentRepository 側の一部に以前の doc_id を残したところ、Pyright が次の型エラーを出しました。

Parameter name mismatch: "doc_id" versus "document_id"

Python では関数をキーワード引数付きで呼べるため、位置専用引数 / を指定しない限り Protocol と実装クラスで仮引数名まで一致させる必要があります。Java では実装クラスの引数名が違ってもエラーなくコンパイルできるため、Python 特有の厳しさでした。

Repository 側のメソッド設計では、作成と更新を分けず save(document) の 1 つにまとめました。Spring Data JPA の save と同じ考え方です。ID の採番やタイムスタンプ設定、PATCH リクエスト時の既存項目とのマージは DocumentService 側で行います。Repository は完成した DocumentResponse を保存する処理だけを担当させました。作成専用の引数を渡す設計にすると更新時に使い回せなくなるためです。

DI の配線は src/practice/dependencies.py に集めています。

_document_repository = InMemoryDocumentRepository()


def get_document_repository() -> DocumentRepository:
    return _document_repository


def get_document_service(
    repository: Annotated[DocumentRepository, Depends(get_document_repository)],
) -> DocumentService:
    return DocumentService(repository)


DocumentServiceDep = Annotated[DocumentService, Depends(get_document_service)]

Annotated は第 1 引数に Pyright 向けの実際の型を置き、第 2 引数以降にフレームワーク向けのメタデータを添える構文です。この形を DocumentServiceDep という型エイリアスにしておくと、ルーター側では型を書くだけで依存が注入されます。依存先を切り替えたくなったときも dependencies.py の変更だけで済みます。

ルーターの list_documents では引数の順序でも一つ学びがありました。

@router.get("", response_model=list[DocumentResponse])
def list_documents(
    service: DocumentServiceDep,
    tag: str | None = None,
    limit: int = Query(default=20, ge=1, le=100),
    offset: int = Query(default=0, ge=0),
) -> list[DocumentResponse]:
    return service.list_documents(tag=tag, limit=limit, offset=offset)

service: DocumentServiceDep にデフォルト値が付いていないため、デフォルト値を持つ tag や limit より前に並べる必要があります。Python では、* 以降のキーワード専用引数を除き、デフォルト値のある引数の後ろにデフォルト値のない引数を書くと構文エラーになります。

レビューで見直したバリデーションの重複と命名

分割と並行して、Step 1-2 から残っていた DocumentCreate と DocumentUpdate のバリデーション重複も整理しました。共通処理をクラス外のヘルパー関数 _normalize_title と _normalize_tags に切り出した際、小さなミスが 2 つありました。

1 つ目は @field_validator からヘルパーを呼び出すときの return 漏れです。Python は return を書かないと暗黙に None を返すため、変換結果が消えてフィールド値が None になってしまいます。2 つ目は @classmethod 由来の cls 引数をそのままヘルパー関数に残していた点で、モジュール直下の通常関数に切り出した後は不要でした。

class DocumentCreate(BaseModel):
    title: str = Field(min_length=1, max_length=200)
    content: str = Field(min_length=1, max_length=50000)
    tags: list[str] = Field(default_factory=list, max_length=10)

    @field_validator("title")
    @classmethod
    def validate_title(cls, v: str) -> str:
        return _normalize_title(v)

    @field_validator("tags")
    @classmethod
    def normalize_tags(cls, tags: list[str]) -> list[str]:
        return _normalize_tags(tags)

あわせてバリデータのメソッド名も、処理手順を並べた tags_trim_and_lower_and_unique のような名前から、役割が伝わる validate_title と normalize_tags に変更しました。

レイヤー分割後は、コードレビューを受けて各層の変数名とメソッド名も揃えました。

DI 導入後にテストがどう変わったか

DI 化の成果が一番はっきり見えたのはテストコードでした。tests/test_documents.py では、27 ケースあるテスト本体のロジックは変えず、ID の変数名を document_id に揃えたうえで client fixture だけを差し替えました。これで全件そのまま成功しました。

@pytest.fixture
def client() -> Iterator[TestClient]:
    repo = InMemoryDocumentRepository()
    app.dependency_overrides[get_document_repository] = lambda: repo
    try:
        with TestClient(app) as client:
            yield client
    finally:
        app.dependency_overrides.clear()

FastAPI の app.dependency_overrides は、元の依存関数をキー、テスト用の関数を値に持つ通常の辞書です。FastAPI は値を関数として呼び出すため、repo そのものではなく lambda: repo を登録します。Java の () -> repo や TypeScript の () => repo に相当する無名関数です。repo は fixture の実行ごとに 1 回だけ生成して閉じ込めています。そのため 1 テスト内の連続リクエストでは同じインメモリ辞書が使われ、テストケースごとの状態は独立して保てます。finally で clear() を呼び、他のテストへ設定が残らないようにしました。

さらに HTTP 層を介さずにビジネスロジックを検証するため、tests/test_document_service.py を追加しました。

@pytest.fixture
def service() -> DocumentService:
    return DocumentService(InMemoryDocumentRepository())


def test_get_document_not_found(service: DocumentService) -> None:
    missing_id = uuid4()
    with pytest.raises(DocumentNotFoundError) as exc_info:
        service.get_document(missing_id)
    assert exc_info.value.document_id == missing_id

Service のインスタンスへ直接 InMemoryDocumentRepository を渡せるため、TestClient を起動せずに単体テストを書けます。存在しない ID に対する 404 変換までは Router 経由の結合テストで検証しつつ、Service 単体では pytest.raises で DocumentNotFoundError と保持する document_id を検証する分担にしました。

修正後に uv run pytest -v を実行すると、API テスト 27 件と Service 単体テスト 6 件の合計 33 ケースがすべて成功し、uv run ruff check . と uv run pyright もエラーゼロになりました。

Python の self や __init__、Protocol、Annotated、lambda といった構文にはまだ迷う場面があります。それでも、Controller・Service・Repository に責務を分けて依存を注入する流れは Spring Boot と同じ考え方です。例外ハンドラで HTTP 応答をまとめる点も共通しています。そのため、分割の方針自体は素直に描けました。次は今回定義した DocumentRepository の実装を差し替える形で、PostgreSQL + SQLAlchemy 2.0 + Alembic による永続化へ進みます。

投稿日: 2026/11/29 9:22:36

好き数: 0

投稿者: ko_tech
zenn.devで見る