API Gateway用にSwaggerからexampleを削除する


はじめに

swaggerファイルからexampleを取り除くnpmライブラリを作ってみました。

以下に公開してあります。

なにができるの?

こんな感じに example が入ったSwaggerがあるとします。

swagger: '2.0'
info:
  description: これはアパートに関するAPIです。
  version: 0.0.1
  title: アパートAPI
paths:
  '/rooms/{room-id}':
    get:
      summary: 部屋情報API
      description: 指定されたroom-idの情報を返します
      parameters:
        - name: room-id
          in: path
          description: 取得したい部屋のID
          required: true
          type: integer
          format: int64
      responses:
        '200':
          description: OK
          schema:
            type: object
            properties:
              id:
                type: integer
                format: int64
                example: 404
              comment:
                type: string
                example: 404号室です。どこにも存在しない部屋かも。

上記を入力すると、下記が出力されます!

swagger: '2.0'
info:
  description: これはアパートに関するAPIです。
  version: 0.0.1
  title: アパートAPI
paths:
  '/rooms/{room-id}':
    get:
      summary: 部屋情報API
      description: 指定されたroom-idの情報を返します
      parameters:
        - name: room-id
          in: path
          description: 取得したい部屋のID
          required: true
          type: integer
          format: int64
      responses:
        '200':
          description: OK
          schema:
            type: object
            properties:
              id:
                type: integer
                format: int64
              comment:
                type: string

example だけ削除されました!
階層のどこにあっても見つけだして消します!

なぜ作った?

Amazon API GatewayにSwaggerファイルをインポートしたところ、以下のようなエラーが発生しました。

errors : [Invalid model schema specified. Unsupported keyword(s): ["example"]]

Swaggerファイルの definitions から example を削除すれば、API Gatewayでエラーは発生しないようですが、Swagger UI では example を使っています。

それなら、普段はexample有り版で書いて、API Gatewayに登録する時だけ example を取り除けばいいじゃない!となりライブラリを作りました。

インストール方法

本ライブラリの使用にはNode.jsが必要です。

Node.jsがインストール済みであれば、以下のコマンドでインストールできます。

npm install swagger-rm-example

使い方

サンプルコードは以下の通りです。

// ライブラリを追加
var fs = require('fs');
var swaggerRmExample = require('swagger-rm-example');

// YAMLファイルを読み込み
var inputFile = "./swagger_input.yaml";
var strInput = fs.readFileSync(inputFile, 'utf8');

// 文字列からexampleを削除
var strOutput = swaggerRmExample.removeExample(strInput);

// 結果を表示
console.log(strOutput);

// YAMLファイル書き出し
var fileOutput = "./swagger_output.yaml";
fs.writeFile(fileOutput, strOutput);

さいごに

これで快適なSwaggerライフが送れそうです。

npmにパッケージを公開するのは初めてでしたが、以下の記事がとてもわかりやすく、予想よりも短時間で済みました。