LoginSignup
3
7

More than 3 years have passed since last update.

アプリ開発でSwagger定義があるならPrismを使おう

Posted at

スマホアプリの開発でバックエンドの人がSwagger定義(Open API Specともいう)を使ってくれてたらPrism使ったら良いよ、というお話。

Prismとは

  • Stoplightという会社が作っている。APIの開発をスムーズに進めていくためのツールを色々提供している。
  • Prismはそのツールのうちの1つで、いわゆるモックサーバー。OSSとして提供されている。
  • 別のサービスだと本家のSwagger UIもレスポンスをモックすることができるし、API Sproutなんかもある。

インストール&使い方

$ npm install -g @stoplight/prism-cli
$ prism mock swagger.yaml

これだけ。簡単。デフォルトで127.0.0.1:4010のポートを使い、読み込んでいたswagger定義ファイルを更新すると自動でリロードもしてくれる。(これがSwagger UIのモックサーバには無い)

レスポンスのカスタマイズ

応答をさせたいSwagger定義にexampleを書くとそれを下にレスポンスを返してくれる。
わからなくなったら本家のDocを読むべし。
https://swagger.io/docs/specification/adding-examples/

方法1: 個別にexampleを設定

(略)
components:
  schemas:
    Pet:
      allOf:
        - $ref: '#/components/schemas/NewPet'
        - type: object
          required:
          - id
          properties:
            id:
              type: integer
              format: int64
              example: 123  # <-- これ

    NewPet:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          example: foo  # <-- これ
        tag:
          type: string
          example: bar  # <-- これ

方法2: まとめてexampleを設定

(略)
components:
  schemas:
    Pet:
      example:  # <-- これ
        id: 999
        name: hoge
        tag: moge
      allOf:
        - $ref: '#/components/schemas/NewPet'
        - type: object
          required:
          - id
          properties:
            id:
              type: integer
              format: int64

    NewPet:
      type: object
      required:
        - name
      properties:
        name:
          type: string
        tag:
          type: string

注意点

方法1、2両方設定するとどうなる?

Prismの場合は方法2の定義が優先されます。

レスポンスの定義に違反するexampleの値はエラーになる?

Prismの場合はエラーになりません。気をつけましょう。

余談

最初はAPI Sproutを使おうとしていたところ、$refを使っている定義を上手くハンドリングできないバグがあるようで、Githubのissueが1年以上放置されているので諦めました。
https://github.com/danielgtaylor/apisprout/issues/40

以上、誰かの役に立てば幸いです。

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