LoginSignup
28
26

More than 3 years have passed since last update.

Swagger UIとSwagger EditorをWebサーバで動かす

Last updated at Posted at 2019-07-04

SwaggerでAPIの定義を記述したいが、インターネットには上げたくなかったり、社内ファイアウォールでデモ版へのアクセスが封じられてるときは、Swaggerをローカルサーバーで起動することになると思います。

ローカルだと各人が環境作らなければならないため、Webサーバに置いて使う方法を紹介します。


Swagger UI

インストール

下記コマンドを実行し、ドキュメントルートに配置するファイルを取得します。

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

ドキュメントルートに配置・確認

ビルド後swagger-ui/distディレクトリをドキュメントルートに配置します。

image.png

デフォルトで読み込むSwaggerファイルを変える

デフォルトで読み込むSwaggerファイルをhttps://petstore.swagger.io/v2/swagger.jsonから任意のURLに変えたい場合は、index.htmlの42行目のURLを任意の値に編集します。

index.html
    window.onload = function() {
      // Begin Swagger UI call region
      const ui = SwaggerUIBundle({
        url: "https://petstore.swagger.io/v2/swagger.json", // 任意のURLを設定
    validatorUrl: null,  // URLバリデーターを無効化
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "StandaloneLayout"
      })
      // End Swagger UI call region

      window.ui = ui
    }

さらにvalidatorUrl: null,を足しておくと、URLのバリデーションチェックを停止できます。

Swagger Editor

インストール

下記コマンドを実行し、ドキュメントルートに配置するファイルを取得します。

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

ドキュメントルートに配置・確認

ビルド後swagger-editor/distディレクトリとswagger-editor/index.htmlをドキュメントルートに配置します。

image.png

デフォルトで読み込むSwaggerファイルを変える

Swagger EditorはクエリストリングでurlをキーにしてURLを渡すとそこのSwaggerファイルを読み込んでくれます。
リンクを張るときにセットしておくか、次のようにソースを修正して、デフォルトで読み込むファイルを変えることができます。

index.html
  window.onload = function() {

    // クエリストリングがなかったら任意のURLをセットして読み込みなおす
    if(location.search == ""){
        window.location.href = window.location.href + "?url=https://petstore.swagger.io/v2/swagger.yaml";
    }

    // Build a system
    const editor = SwaggerEditorBundle({
      dom_id: '#swagger-editor',
      layout: 'StandaloneLayout',
      presets: [
        SwaggerEditorStandalonePreset
      ]
    })

    window.editor = editor
  }

以上でした。

28
26
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
28
26