2023/12/15

使用 Swagger UI 來為你的 Express 應用程式中的路由生成 API 說明文件

作者:吳祐賓

 


 

 

使用 Swagger UI 來為你的 Express 應用程式中的路由生成API說明文件。Swagger UI 提供了一個直觀且互動的方式,讓開發者能夠查看和測試你的 API。

以下是如何將 Swagger UI 整合到你的 Express 應用程式中的基本步驟: 


安裝 Swagger UI 套件

使用以下指令安裝:

npm install swagger-jsdoc swagger-ui-express



設定 Swagger 設定檔案:

在你的專案中建立一個 swagger.js 檔案,用於配置 Swagger UI。例如:

const swaggerJsdoc = require('swagger-jsdoc');

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Express API with Swagger',
      version: '1.0.0',
      description: 'Documentation for Express API',
    },
  },
  apis: ['./app/*.js'], // 指定 API 路徑,這裡可能需要調整
};

const specs = swaggerJsdoc(options);

module.exports = specs;



設定 Swagger UI 中介軟體:

在 server.js 中,加入以下程式碼:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const specs = require('./swagger');

const app = express();

// ... 其他程式碼 ...

// 設定 Swagger UI 中介軟體
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});

在這裡,我們將 Swagger UI 中介軟體掛載到 /api-docs 路徑上,它將使用先前定義的 Swagger 設定檔案(specs)。



註解你的路由:

在 server.js 檔案中,使用 Swagger 註解來描述每個路由的信息。以下是一個簡單的範例:

/**
 * @swagger
 * tags:
 *   name: Strings
 *   description: Operations related to strings
 */

/**
 * @swagger
 * /echo_string/{value}:
 *   get:
 *     summary: Echoes the input string
 *     tags: [Strings]
 *     parameters:
 *       - in: path
 *         name: value
 *         required: true
 *         description: The string to be echoed
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: Successful response
 *         content:
 *           application/json:
 *             example: { result: "input_string" }
 */

app.get('/echo_string/:value', (req, res) => {
  res.json({ result: serverMethods.echoString(req.params.value) });
});

/**
 * @swagger
 * /reverse_string/{value}:
 *   get:
 *     summary: Reverses the input string
 *     tags: [Strings]
 *     parameters:
 *       - in: path
 *         name: value
 *         required: true
 *         description: The string to be reversed
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: Successful response
 *         content:
 *           application/json:
 *             example: { result: "gnirts_tupni" }
 */

app.get('/reverse_string/:value', (req, res) => {
  res.json({ result: serverMethods.reverseString(req.params.value) });
});

這樣的註解會被 Swagger 解析,並顯示在 Swagger UI 中。



執行應用程式:

最後,執行 node server.js,並瀏覽網址 http://localhost:3000/api-docs,你應該能夠看到 Swagger UI,其中包含你的 API 說明文件。畫面應該長得像下圖的圖片。



這樣就完成了 Swagger UI 的整合。透過 Swagger,你能夠更容易地為你的 API 提供說明文件,並讓開發者更容易了解和使用你的 API。


和你分享。


See also

文首圖片來源:攝影師:Karolina Grabowska: https://www.pexels.com/zh-tw/photo/4476376/


沒有留言:

張貼留言