---
# System prepended metadata

title: Swagger

---

官方網站：https://swagger.io/

## 說明
自動偵測程式專案中的 RESTful API產生文件，其中會列出API 的規格，包含 HTTP 方法、參數、request 與 response body 等。這份文件可在網頁上供人觀看，甚至能直接用來呼叫，十分便利。

## 安裝Swagger
1. 進入 express 專案中(在Impact Copilot中是api-gateway資料夾)
2. 安裝相關套件：
    ```
    npm install swagger-ui-express
    npm install --save-dev swagger-autogen # 只在開發時自動產生 JSON
    ```
3. 在專案的根目錄中建立「swagger.js」檔案並加入以下內容
    ```js
    const swaggerAutogen = require('swagger-autogen')(); 

    const doc = { 
      info: {
        title: 'My API', 
        description: 'Description'
      },
      host: 'localhost:3000'
    };

    const outputFile = './swagger-output.json'; 
    const routes = ['./app.js']; 

    /* NOTE: If you are using the express Router, you must pass in the 'routes' only the 
    root file where the route starts, such as index.js, app.js, routes.js, etc ... */

    swaggerAutogen(outputFile, routes, doc); 
    ```
    * swaggerAutogen：引入 swagger-autogen 模組並初始化
    * doc：Swagger API 文件的基本資訊
    * outputFile：指定輸出的檔案名稱和路徑，產出的 Swagger 文件會寫到這裡
    * routes：指定要掃描的路由檔案，這裡所有路由都會寫在app.js中
    * swaggerAutogen()：呼叫 swaggerAutogen()，掃描你指定的檔案（routes），然後根據其中的註解和 doc 設定，自動產生 Swagger JSON 文件，寫進 outputFile
4. 在package.json中加入
    ```json
    "scripts": {
        ...
        "swagger": "node ./swagger.js"
    }
    ```
    (Impact_Copilot專案中要用./src/swagger.js)
6. 執行 `npm run swagger` (會自動產生swagger-output.json)
7. 在app.js中加入以下內容，讓swagger-ui運行在express中
    ```js
    const swaggerUi = require('swagger-ui-express') //導入swaggerUI
    const swaggerFile = require('./swagger-output.json') // 讀取剛剛生成的swagger-output.json文件

    app.use('/api-doc', swaggerUi.serve, swaggerUi.setup(swaggerFile)) //這行要在const app = express();之下
    ```
9. 執行 `npm start`
10. 在網頁中輸入 `http://localhost:9000/api-doc/` 即可看到生成的api文件(impact-copilot路徑為 `http://localhost:9000/api/docs/#/)`
![image](https://hackmd.io/_uploads/rJ78-D0Ele.png)
p.s. 預設會導到 http://localhost:9000/ 若要改成自動導向/api-doc/可以加上
    ```
    app.get('/', (req, res) => {
      res.redirect('/api-doc');
    });
    ```
* swagger-ui-express：讓 Express 支援 swagger 的 UI 介面
* swagger-autogen：執行autogen時自動依照api router中的註解內容生成 API 文件。執行autogen會產生一個json檔，ui依照這個json檔在網頁上呈現
* 參考資料
[swagger autogen](https://www.npmjs.com/package/swagger-autogen)
[Swagger aurogen homepage](swagger-autogen.github.io)
