LoginSignup
3
3

More than 3 years have passed since last update.

【OpenAPI】定義ファイルを分割して管理する

Last updated at Posted at 2020-11-27

はじめに

そこそこの規模のアプリでOpenAPIを導入すると、1つのYAMLファイルで管理し続けるには限界があります。定義ファイルの分割と、分割した定義ファイルの参照について情報をまとめました。

対象バージョン

OpenAPI Specification Version 3.0.3

定義ファイルの分割

肥大化していたり、使い回すことの多いスキーマやコンポーネントを中心に、別ファイルに切り出します。
切り出したファイルは、参照元が参照できる任意の構成で設置することができます。
個人的には、OpenAPIのコンポーネント構造と同じディレクトリ構成にすると直感的で分かりやすいと感じています。

ディレクトリ構成例
openapi.yaml
paths/
    items.yaml
components/
    schemas/
        item.yaml

参照

別ファイルに記載したスキーマ等を呼び出すには $ref を用います。ファイルパスは相対パスで指定します。

Using $ref - swagger.io

openapi.yaml
# 省略

paths:
  /items:
    $ref: "paths/items.yaml"  # paths ディレクトリ内の items.yaml ファイルを参照する

components:
  schemas:
    Item:  # 別の箇所からスキーマ名で参照できるようになる
      $ref: "components/schemas/item.yaml"
paths/items.yaml
# 省略

responses:
  200:
    content:
      application/json:
        schema:
          type: array
          items:
            # openapi.yaml で定義したスキーマを参照する場合
            $ref: "../openapi.yaml#/components/schemas/Item"  

            # 直接ファイルを参照する場合
            $ref: "../components/schemas/item.yaml"

定義ファイルの記述にVSCodeを使用していれば、拡張機能をインストールすることで参照先にコードジャンプできるようになります。

OpenAPI (Swagger) Editor

定義ファイルのバンドル

ツールを使って定義ファイルをバンドルします。

swagger-cli

参考

3
3
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
3
3