👻

Swagger EditorでOpenAPIを書く方法|info・paths・schemasの基本

に公開

はじめに

前回は「Swagger EditorとSwagger UIの違い」を整理しました。
今回はSwagger Editorを使って、実際にAPI仕様を記述する流れを
エリアごとに分けて サンプル付きで解説します。

例:ユーザー取得API

今回は「ユーザー情報をIDで取得するAPI」を例にします。

openapi: 3.0.3
info:
  title: User API
  version: 1.0.0
  description: ユーザー管理用のAPI
servers:
  - url: https://api.example.com
    description: 本番環境
paths:
  /users/{id}:
    get:
      summary: ユーザー情報を取得
      parameters:
        - in: path
          name: id
          required: true
          schema:
            type: string
          description: ユーザーID
      responses:
        "200":
          description: 正常応答
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
              example:
                id: "123"
                name: "Hanako"
                age: 29
        "404":
          description: ユーザーが存在しない
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                code: NOT_FOUND
                message: 指定されたIDは存在しません
components:
  schemas:
    User:
      type: object
      required: [id, name]
      properties:
        id:
          type: string
          description: ユーザーID
        name:
          type: string
          description: 氏名
        age:
          type: integer
          minimum: 0
          description: 年齢
    Error:
      type: object
      required: [code, message]
      properties:
        code:
          type: string
          description: エラーコード
        message:
          type: string
          description: エラーメッセージ

基本情報エリア(info / servers)

ここではAPI全体の基本情報を定義します。

openapi: 3.0.3
info:
  title: User API
  version: 1.0.0
  description: ユーザー管理用のAPI
servers:
  - url: https://api.example.com
    description: 本番環境
  • title:APIの名前(例:User API)
  • version:APIのバージョン
    形式は 1.0.0 のような Semantic Versioning (セマンティックバージョニング) が一般的です。

破壊的変更(既存クライアントが動かなくなる変更) → メジャーバージョンを上げる (1.x.x → 2.0.0)
後方互換のある追加(項目追加、新エンドポイント追加など) → マイナーバージョンを上げる (1.1.0)
修正や微調整(typo修正、説明追記など) → パッチバージョンを上げる (1.1.1)

  • description:このAPIが何をするものかの概要
  • servers:利用するサーバーURL(本番・ステージング・ローカル環境など)
    APIを利用するベースURLです。本番・ステージング・ローカルなど、複数書けます。
servers:
  - url: https://api.example.com
    description: 本番環境
  - url: https://staging-api.example.com
    description: ステージング環境
  - url: http://localhost:8080
    description: ローカル開発環境

パスエリア(paths)

APIのエンドポイントごとの仕様を定義します。

paths:
  /users/{id}:
    get:
      summary: ユーザー情報を取得
      parameters:
        - in: path
          name: id
          required: true
          schema:
            type: string
          description: ユーザーID
  • /users/{id}:ユーザーIDを受け取るパス
    /users/{id} は「ユーザーリソースの中から、特定のユーザーIDを指定する」

例:/users/123 → ユーザーID「123」の情報を取得
  /users/abc → ユーザーID「abc」の情報を取得

  • get:HTTPメソッド(今回は取得なのでGET)
    URLに対して「何をしたいのか」を表す動詞のようなものです。

主に使うのはこの5つです。

メソッド 意味
GET データを取得 /users/123 → ユーザー情報を取得
POST データを新規作成 /usersに新規ユーザーを追加
PUT データを全体更新 /users/123の情報を丸ごと更新
PATCH データを部分更新 /users/123の「名前だけ変更」など
DELETE データを削除 /users/123を削除

よくある誤解:「GET /deleteUser」みたいに動詞をパスに入れるのはREST的にはNG。
→ パスは名詞、メソッドが動詞の役割を担う、というルールが基本です。

  • summary:このAPIの簡単な説明(今回は取得なのでGET)
  • parameters:入力パラメータ
    1. Path パラメータ
      • URLの一部に埋め込む形式
      • 必須 (required: true) が原則
      parameters:
        - in: path
          name: id
          required: true
          schema:
            type: string
          description: ユーザーID
      
    2. Query パラメータ
      • URLの「?」以降につけるもの
      • フィルタリングや検索条件でよく使う
       parameters:
         - in: query
           name: ageMin
           schema:
             type: integer
           description: 年齢の下限
      
    3. Header パラメータ
      • HTTPヘッダーで渡す情報
      • 認証トークンや言語設定などで利用
      parameters:
        - in: header
          name: X-Request-Id
          schema:
            type: string
          description: トレース用のリクエストID
      

入力パラメータのイメージたとえ

  • Path:手紙の「宛先住所」
  • Query:宛先に「追伸: 年齢20以上だけ教えて」みたいに条件を追加
  • Header:封筒に貼る「速達」「航空便」「本人限定」などのラベル

レスポンスエリア

レスポンスの内容をステータスコードごとに定義。

      responses:
        "200":
          description: 正常応答
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
              example:
                id: "123"
                name: "Hanako"
                age: 29
        "404":
          description: ユーザーが存在しない
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                code: NOT_FOUND
                message: 指定されたIDは存在しません
  • **"200"**→ HTTPステータスコード。成功を意味します。

    よく使うステータスコード

    • 200:成功(正常レスポンスあり)
    • 201:リソース作成成功(POSTで新規作成したとき)
    • 204:成功したが返す内容なし(DELETEやPUTのときによく使う)
    • 400:リクエスト不正(パラメータ不足・形式エラーなど)
    • 401:認証エラー(トークン無効など)
    • 403:権限エラー(アクセス禁止)
    • 404:リソースが存在しない
    • 500:サーバー内部エラー
  • content.application/json → レスポンスの形式

  • schema → レスポンスの型定義を参照。ここでは #/components/schemas/User を呼んでいます。

スキーマエリア(components/schemas)

APIの リクエストボディやレスポンスのデータ構造 を定義する場所。
同じ型(オブジェクト)を複数のAPIで使うときに 再利用できる

components:
  schemas:
    User:
      type: object
      required: [id, name]
      properties:
        id:
          type: string
          description: ユーザーID
        name:
          type: string
          description: 氏名
        age:
          type: integer
          minimum: 0
          description: 年齢
    Error:
      type: object
      required: [code, message]
      properties:
        code:
          type: string
          description: エラーコード
        message:
          type: string
          description: エラーメッセージ
  • type: object→ このスキーマはオブジェクト
  • required→ 必須フィールドのリスト
  • properties→ 各プロパティの型、説明、制約を書く

代表的な型(type)の例

説明 よく使う補足(format / 制約など)
string 文字列 format: を指定可能(例:date-time, email, uuid, uri "Hanako"
integer 整数値 minimum, maximum で範囲指定 29
number 数値(整数・小数両方) format: float, format: double で精度指定 3.14
boolean 真偽値 true / false のみ true
array 配列 items: で要素の型を指定 ["A","B","C"]
object オブジェクト properties にキーと型を定義 { "id": "123", "name": "Hanako" }

補足ポイント

  • string は用途が広く、format を指定できるのが便利

    • 例: date-time(日時)、emailuuiduri
  • integer と number の違い

    • integer → 小数なし(例:29)
    • number → 小数もOK(例:3.14)
  • arrayitems で要素の型を指定

    • 例:array of object としてオブジェクトの配列も表現可能
  • objectproperties に複数のキーと型を定義できる

    • ネストして入れ子構造を作ることも可能
    • 複雑なJSONレスポンスを再現できる

まとめ

Swagger Editorでは、OpenAPIを以下のエリアに分けて定義します。

  • 基本情報エリア:APIの名前、バージョン、サーバーURL
  • パスエリア:エンドポイントごとの仕様(パラメータ、レスポンス)
  • レスポンスエリア:共通レスポンスをまとめる場所
  • スキーマエリア:データ構造を定義する場所
    このようにエリアごとに分けて考えると、「どこに何を書けばいいか」が整理され、実装やテストへの落とし込みがスムーズになると思います。

Discussion