はじめに
業務でバックエンドを担当することが多く、フロントエンド担当者と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仕様を確認
ブラウザで確認
JSONを確認
ファイル出力したい場合はGitBashで以下のコマンドを実行。
curl http://localhost:8000/openapi.json > openapi.json
VSCode上で確認
拡張機能 OpenAPI (Swagger) Editorをインストールする。42crunch.vscode-openapi
VSCodeでOpenAPIのJSONを開くと右上にプレビューアイコンが表示されるのでクリック。

VSCode上でも確認が可能。

