はじめに
こんにちは、プログラミングを始めて約3年のエンジニアのkeitaMaxです。
この記事にあるように、Swagger UIを使用してブラウザでドキュメントをみようと思います。
前回の記事
swagger.json
ファイルの作成
記事にあるように、swagger-xxx.php
ファイルを作成してみます。
今回は、appフォルダ下にswagger-001.php
として作成しました。
<?php
/**
* @SWG\Swagger(
* host="http://api.example.com",
* schemes={"http", "https"},
* @SWG\Info(
* version="1.0",
* title="xxx のAPIドキュメント",
* ),
* )
*/
そして以下のコマンドを実行して、swagger.json
を作成します。
./vendor/bin/openapi app -o public/swagger.json
これで以下のようにswagger.json
が作成されました。
{
"openapi": "3.0.0",
"paths": {
"/posts": {
"get": {
"operationId": "5f292ed47bdbfa79356750be0807450c",
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "Not allowed"
}
}
},
"post": {
"operationId": "c2e0b0e26215e6d34ece33ebae25f7df",
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "Not allowed"
}
}
}
},
"/posts/create": {
"get": {
"operationId": "87880105c55ee709353642ef648ce4ec",
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "Not allowed"
}
}
}
},
"/posts/{id}": {
"get": {
"operationId": "c8bd68bc05422c879bc2dd429ae5782b",
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "Not allowed"
}
}
},
"put": {
"operationId": "06c81121178208730e11d2f6b655e78d",
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "Not allowed"
}
}
},
"delete": {
"operationId": "54788a50da690c5ee1dfdc25425a1f87",
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "Not allowed"
}
}
}
},
"/posts/{id}/edit": {
"get": {
"operationId": "21af8f810c09713b3cf9987a1624e4fd",
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "Not allowed"
}
}
}
}
}
}
こんな感じでswagger.json
ファイルが作成されました。
ブラウザでswagger.json
を見れるようにする
リンクからdistフォルダをダウンロードし、含まれているindex.html内にてswagger.jsonを読み込んでいる箇所(40行目付近)を探します。
(引用:https://qiita.com/wrbss/items/258394193e5ffd1b926a)
これの通りに行なっていきます。
LaravelのPublic下に'swagger'ファイルを作成します。
その後、Gitから全てZipファイルでダウンロードし、dist
フォルダ以下をすべてコピーして先ほど作成したswagger
フォルダの中に貼り付けます。
swagger-initializer.jsテキスト エディターで開き、「 https://petstore.swagger.io/v2/swagger.json」を OpenAPI 3.0 仕様の URL に置き換えます。
(引用:https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md)
swagger-initializer.js
を以下のように修正します。
window.onload = function() {
//<editor-fold desc="Changeable Configuration Block">
// the following lines will be replaced by docker/configurator, when it runs in a docker-container
window.ui = SwaggerUIBundle({
url: "../swagger.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
//</editor-fold>
};
そして、以下のURLをブラウぜで表示します。
※Dockerで8081ポートでアクセスできるようにしています。
http://localhost:8081/swagger/index.html
すると、以下のようにドキュメントを確認することができます。
おわりに
この記事での質問や、間違っている、もっといい方法があるといったご意見などありましたらご指摘していただけると幸いです。
最後まで読んでいただきありがとうございました!
参考