OpenAPI Specificationを用いてAPIの定義を記述するときに、APIが増えると定義ファイルが肥大化して内容を把握しにくくなる。
そのため、定義ファイルを分割して管理する方法を検討した。
(現時点での最新versionは3.1.0であるが、実装がまだ進んでいないので、3.0.3で検討した)
方法
カテゴリごとに別々の定義ファイルを作る。この定義ファイルは単体でOpenAPI Specificationに準拠して作成する。そのためエディタでは分割した定義ファイルごとにプレビューしながら編集できる。
分割した定義ファイルを一つのファイルにまとめるには、Path Item Objectの$refフィールドを使って、分割したファイルで定義したPath Itemを参照する。
pathを参照するときに、階層の区切りを/(スラッシュ)で表すため、エンドポイントに含まれるスラッシュは~1にエスケープする。
例
openapi: "3.0.3"
info:
version: 1.0.0
title: Swagger Store
license:
name: MIT
servers:
- url: http://bookstore.swagger.io/v1
paths:
/pets:
$ref: "petstore.yaml#/paths/~1pets"
/books:
$ref: "bookstore.yaml#/paths/~1books"
openapi: "3.0.3"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
tags:
- books
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
examples:
- 20
responses:
'200':
description: A paged array of books
content:
application/json:
schema:
$ref: "#/components/schemas/pets"
components:
schemas:
Pet:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
openapi: "3.0.3"
info:
version: 1.0.0
title: Swagger Bookstore
license:
name: MIT
servers:
- url: http://bookstore.swagger.io/v1
paths:
/books:
get:
summary: List all books
tags:
- books
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
examples:
- 20
responses:
'200':
description: A paged array of books
content:
application/json:
schema:
$ref: "#/components/schemas/books"
components:
schemas:
book:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
books:
type: array
items:
$ref: "#/components/schemas/book"
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
参考
https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathItemObject
https://swagger.io/docs/specification/using-ref/