0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FastAPI×OpenAPI コード→ドキュメント出力メモ

Posted at

はじめに

業務でバックエンドを担当することが多く、フロントエンド担当者とAPIのI/Fのやりとりをすることが多いので、OpenAPIで仕様書を自動生成するときのお作法を記事化しました。
毎回調べなおして求めている記事を探すのが大変なので、自分用メモとして投稿しよう的な。

以前作成したPython(FastAPI)のプロジェクトで試してみました。

Pydanticのインストール

Git bashで以下のコマンドを実行。

poetry add pydantic

プロジェクト構成

Gemini氏のアドバイスを参考にしつつこの構成とする。

.
├── app/
│   ├── __init__.py
│   ├── main.py  # ルーターをインポートして集約
│   ├── endpoints/
│   │   ├── __init__.py
│   │   ├── hoges_endpoints.py
│   └── schemas/
│       ├── __init__.py
│       ├── hoges_schemas.py
│       └── fugas_schemas.py

Pydanticモデル作成

リクエストボディ、レスポンスボディの入れ物となるModel(?)を作成する。

schemas/hoges_schemas.py
from typing import List, Literal, Optional

from pydantic import BaseModel


class PiyoElement(BaseModel):
    piyopiyo: str


class HogeIreko(BaseModel):
    hoge: str
    fuga: float


class Hoge(BaseModel):
    name: str
    age: Optional[float]
    blood_type: Literal["A", "B", "O", "AB"]
    is_hoge: bool
    ireko_model: HogeIreko
    piyo_list: List[PiyoElement]

エラーを返す時用の入れ物も用意しておく。

schemas/error_schemas.py
from pydantic import BaseModel


class HogeFugaError(BaseModel):
    status: int
    message: str

エンドポイント作成

とりあえずGETとPOSTを1つずつ。

endpoints/hoge_endpoints.py
from fastapi import APIRouter

from schemas.error_schemas import HogeFugaError
from schemas.hoges_schemas import Hoge

router = APIRouter()


@router.get(
    "/hoges/{hoge_id}",
    description="ほげを取得します。",
    summary="summary=URLの横に表示されるやつ",
    responses={
        200: {"model": Hoge, "description": "正常系でござる"},
        500: {"model": HogeFugaError, "description": "システムエラー"},
    },
)
def read_hoge(hoge_id: int, query_param: str):
    return "success"


@router.post("/hoges")
def create_hoge(hoge: Hoge):
    return

main.pyに集約する。

main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from endpoints import hoge_endpoints

app = FastAPI()

# 各エンドポイントモジュールをインルード
app.include_router(hoge_endpoints.router, tags=["タグという概念で一括りにできる"])


@app.get("/")
def read_root():
    return {"message": "Welcome to the API"}

生成されたAPI仕様を確認

ブラウザで確認

スクリーンショット_29-9-2025_155913_localhost.jpeg

JSONを確認

ファイル出力したい場合はGitBashで以下のコマンドを実行。

curl http://localhost:8000/openapi.json > openapi.json

VSCode上で確認

拡張機能 OpenAPI (Swagger) Editorをインストールする。42crunch.vscode-openapi

VSCodeでOpenAPIのJSONを開くと右上にプレビューアイコンが表示されるのでクリック。
image.png

VSCode上でも確認が可能。

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?