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ディレクトリをドキュメントルートに配置します。

デフォルトで読み込む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をドキュメントルートに配置します。

デフォルトで読み込む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
  }

以上でした。

元記事はこちら

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