在 Laravel 10.0 使用 Redocly CLI 整合 Swagger UI 文件工具

建立專案

建立專案。

1
2
laravel new laravel-swagger-ui
cd laravel-swagger-ui

安裝 Swagger UI

手動從 Swagger UI 的 GitHub 下載原始碼。也可以使用以下指令下載,並解壓縮。

1
2
3
wget $(curl -s https://api.github.com/repos/swagger-api/swagger-ui/releases/latest | jq -r ".zipball_url") -O swagger-ui-latest.zip
unzip -d swagger-ui-latest swagger-ui-latest.zip
rm swagger-ui-latest.zip

將其中的 dist 資料夾,移動到專案的 public/docs 資料夾。

1
2
cp -r $(find swagger-ui-latest -type d -name "dist" -print -quit) public/docs
rm -rf swagger-ui-latest

修改 index.html 檔,修正靜態檔案引入的相對路徑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
<link rel="stylesheet" type="text/css" href="./index.css" />
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
</head>

<body>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js" charset="UTF-8"> </script>
<script src="./swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
<script src="./swagger-initializer.js" charset="UTF-8"> </script>
</body>
</html>

修改 swagger-initializer.js 檔,修正 url 欄位。

1
2
3
4
5
6
window.onload = function() {
window.ui = SwaggerUIBundle({
url: "./spec.json",
// ...
});
};

安裝 Redocly CLI

安裝依賴套件。

1
npm install @redocly/cli nodemon -D

修改 package.json 檔,建立一個腳本。

1
2
3
4
5
6
{
"scripts": {
"docs:build": "redocly bundle docs/openapi.yaml --output public/docs/spec.json --ext json",
"docs:watch": "nodemon --watch docs/openapi.yaml -x \"npm run docs:build\""
}
}

建立文件

在專案根目錄建立 docs/openapi.yaml 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
openapi: 3.0.3

info:
title: JSONPlaceholder
description: Free fake API for testing and prototyping.
version: 0.1.0

paths:
"/posts":
get:
tags: ["posts"]
summary: Returns all posts
responses:
"200":
description: All went well
content:
application/json:
schema:
$ref: "#/components/schemas/post"
components:
schemas:
post:
type: object
properties:
id:
type: number
description: ID of the post
title:
type: string
description: Title of the post
body:
type: string
description: Body of the post

編譯文件。

1
npm run docs:build

啟動專案。

1
php artisan serve

瀏覽文件

前往 http://localhost:8000/docs 瀏覽。

程式碼

參考文件