LoginSignup
23
19

More than 5 years have passed since last update.

JSON (Hyper)Schemaの書き方に対する一つの例

Last updated at Posted at 2016-06-01

JSON Schemaを用いた各種ライブラリやMarkdown生成ツールなどが出てきているが、実際に運用しようとしたときに試行錯誤し、最終的に落ち着きそうな形が見えてきたので共有したい。

良さそうな書き方

ファイルを分割しない。するならHyperSchemaファイルごとに

JSON (Hyper)Schemaファイルを書くと一瞬で行数が巨大化する。
そのため現状では、各Schemaファイルをツールにより結合して巨大な一枚のファイルに結合する方法があり、prmdが用いられているのをよく見る。

ただこれにはいくつか問題があり、

  • 結合後のSchemaにより発生したエラーを追いにくい
  • 各ファイルで定義されたSchemaを参照する際に、エディタなどの補助がなければ辛い

をどうするかという話が出てくる。
全体を一枚のファイルで書くと、極めて原始的だが、参照性の問題や、
結合の方法が原因のエラーを考えなくて済むため、だいぶ楽になる。

definitionsはトップレベルのSchemaのみでやる、

各columnの定義をトップレベルのSchemaのdefinitionsに書き、Links内にある各API定義ではdefinitionsを用いず、$ref(おそらくJSON Pointerという名前)で参照するという形を取る。
そうするとSchemaファイルの肥大化に対しても比較的シンプルさを保てる

常識的な範囲のAPI設計にする

JSON Schemaはとても柔軟なので、あまりにも凄まじいものも定義出来るが、できるからといってしない。

具体的に上記の例を踏まえながらサンプルをyamlで書くと

example.yml

title: sample
description: sample API Schema

definitions:

    user_id:
        type: string
        description: user id
        example: 1

    user_name:
        type: string
        description: user secreen name
        example: bar

    user:
        type: object
        title: User
        description: User
        properties:
            user_id:
                $ref: '#/definitions/user_id'
            screen_name:
                $ref: '#/definitions/user_name'
    users:
        type: array
        description: user list
        items:
            $ref: '#/definitions/user'

href: https://sample-app
links:
    - title: GET /users
      description: get user list
      rel: self
      href: /user
      method: GET
      targetSchema:
          $ref: '#/definitions/users'


という感じになる

23
19
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
23
19