ぺーぺーSEのブログ

備忘録・メモ用サイト。

Swagger入門

Swaggerとは

SwaggerとはREST APIを記述する標準仕様。
MS、Google、IBMなどがRESTful APIの記述標準化を目指す「Open API Initiative」を立ち上げ、Swaggerベースで活動している。
SwaggerはSwagger / OpenAPI Spec 2.0に準拠したJSONYAMLで記述する。
以降このJSON・YAMLで記載するSwaggerの定義ファイルをSwagger-Specと呼ぶ。
Swaggerの主要なツールに以下がある。

  • Swagger Editor
    • Swagger-Spec記述用のエディタ
    • Node.jsで起動し、ブラウザから使用する
    • Mockサーバのソースコードを出力する機能(後述のSwagger Codegen使用)も持ち、APIテストも実施できる
    • Webでも公開されている
  • Swagger UI
    • Swagger-Specを読み込み、HTML形式のドキュメントを生成するツール
    • Webでサンプルが公開されている
  • Swagger Codegen
    • Swagger-Specからクライアント・サーバコードを生成するコマンドラインツール
    • 多くの言語、フレームワークに対応している

上記以外にもいろいろある。
Swaggerの定義ファイルの書き方はここ

使い方

Swagger Editor

npm前提。

$ git clone https://github.com/swagger-api/swagger-editor.git
$ cd swagger-editor
$ npm install
$ npm run build
$ npm start

勝手に「http://localhost:8080」でブラウザが開く。
「File」タブから新規Swagger-Spec作成、インポート、エキスポート(JSON、YAML)ができる。
「Generate Server」「Generate Client」タブから編集中のSwagger-Specに基づいてクライアント・サーバコードを生成できる。
ここでは、「Generate Server」→「Spring MVC」を選択してみた。
zipを解凍するとMavenプロジェクトになっており、mvn jetty:runでMockサーバを起動することができる。
http://localhost:8002/api-docs」にアクセスするとJSON形式でSwagger-Specを取得できる。

Dockerで起動

なお、Swagger EditorはDockerでも提供されている。

$ docker pull swaggerapi/swagger-editor
$ docker run -d -p 8001:8080 swaggerapi/swagger-editor

上記が完了したら、ブラウザでhttp://xxx.xxx.xxx.xxx:8001へアクセスし、エディタを起動する。
なお、エンドポイントのIPはdocker-machine ip defaultコマンドなどで確認する。

Swagger UI

同じくnpm前提。

$ git clone https://github.com/swagger-api/swagger-ui.git
$ cd swagger-ui
$ npm install

「.dist/index.html」を開く。
Swagger Editor節で紹介したサーバを起動した状態で、Swagger UI上部のテキストボックスに「http://localhost:8002/api-docs」と入れてExploreするとAPIドキュメントが表示される。

注意

Swagger UI上部のテキストボックスにSwagger(JSON)のパスを入力してExploreする際、CORSで引っかかる。

blog.pepese.com

Google Chromeの場合は「--disable-web-security」をつけて起動すると回避できる。ただし、Chromeのプロセスは一度全て停止しないと反映されない。

Dockerで起動

Swagger UIもDocker提供されている。
こちらはDockerfileが提供されているのでビルドする形になる。

$ git clone https://github.com/swagger-api/swagger-ui.git
$ cd swagger-ui
$ npm install

Swagger Editorで作成したSwagger-Specをswagger.yamlとすると、これをdist/配下に配備する。
その上で以下のコマンドを実行。

$ docker build -t swagger-ui-builder .
$ docker run -d -p 8000:8080 swagger-ui-builder

これで、api-docsを提供するサーバ作成も、CORS対策もする必要がなく、ブラウザでhttp://xxx.xxx.xxx.xxx:8000へアクセスして、http://xxx.xxx.xxx.xxx:8000/swagger.yamlを見るだけでAPIドキュメントを閲覧することができる。

その他話題

Validationエラー

ローカル環境のSwagger UIでAPIドキュメント見る際、Validationエラーが発生する。
特に問題ないが、目障りであればdist/index.html(51行目あたり)を以下のように修正する。

window.swaggerUi = new SwaggerUi({
  url: url,
  validatorUrl: undefined, // !!!この行を追記!!!
  dom_id: "swagger-ui-container",
  supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
  onComplete: function(swaggerApi, swaggerUi){
    if(typeof initOAuth == "function") {
      initOAuth({
        clientId: "your-client-id",
        clientSecret: "your-client-secret-if-required",
        realm: "your-realms",
        appName: "your-app-name",
        scopeSeparator: " ",
        additionalQueryStringParams: {}
      });
    }

デフォルトのSwagger-Specエンドポイント

Swagger UIはデフォルトでhttp://petstore.swagger.io/v2/swagger.jsonを見に行くようになっている。
dist/index.htmlの40行目あたりにある以下コードを修正すれば変更することができる。

        // url = "http://petstore.swagger.io/v2/swagger.json";
        url = "http://192.168.99.100:8000/swagger.yaml";

AWS API Gateway

なんとAWSAPI Gatewayに設計したSwaggerをインポートすると設計通りのAPI Gatewayを構築できるらしい。

公式:
https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/apis.html

Amazon API Gateway Importer:
https://github.com/awslabs/aws-apigateway-importer/blob/master/README.md