Node.js中Swagger的使用指南詳解
Swagger(目前用OpenAPI Specification代替)是一個用于設計、構建、記錄和使用REST API的強大工具。通過使用Swagger,開發(fā)者可以定義API的結構,確保API的穩(wěn)定性,并生成協(xié)作所需的文檔。本文將探討使用Swagger的一些關鍵技巧,包括如何定義API、如何生成和展示文檔等。
安裝和配置Swagger
在Node.js項目中,可以利用swagger-ui-express
和swagger-jsdoc
等工具來集成Swagger。這些工具能夠幫助記錄API和生成一個交互式的用戶界面,用于測試API。
首先安裝依賴:
npm install swagger-jsdoc swagger-ui-express --save
初始化Swagger JSDoc
在項目中初始化Swagger JSDoc以自動生成API文檔。這通常在應用程序的入口文件(比如app.js
或server.js
)進行配置。
const swaggerJSDoc = require('swagger-jsdoc'); const swaggerUi = require('swagger-ui-express'); const swaggerDefinition = { openapi: '3.0.0', // 使用OpenAPI Specification 3.0版本 info: { title: '我的API文檔', version: '1.0.0', description: '這是我的API文檔的描述', }, servers: [ { url: 'http://localhost:3000', description: '開發(fā)服務器', }, ], }; const options = { swaggerDefinition, apis: ['./routes/*.js'], // 指向API文檔的路徑 }; const swaggerSpec = swaggerJSDoc(options); // 使用swaggerUi提供可視化界面 app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
確保把apis
的路徑設置成包含有注釋的API文件所在的路徑。
使用JSDoc注釋編寫文檔
為了讓swagger-jsdoc
能夠生成Swagger文件,需要在路由文件或控制器文件中添加JSDoc注釋。
/** * @swagger * /users: * get: * tags: [Users] * summary: 獲取用戶列表 * description: "返回當前所有用戶的列表" * responses: * 200: * description: 請求成功 * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/User' */
上面的注釋定義了GET /users
路由,并指定了其行為和預期的響應。
定義模型
為了更好地復用和管理代碼,可以在Swagger文檔中定義模型(或稱為schema)。
/** * @swagger * components: * schemas: * User: * type: object * required: * - username * - email * properties: * id: * type: string * description: 用戶唯一標識 * username: * type: string * description: 用戶名 * email: * type: string * format: email * description: 用戶郵箱地址 */
這個模型定義了一個User
對象,它有id
、username
和email
屬性。
Swagger UI的使用
啟動Node.js應用后,通過訪問http://localhost:3000/api-docs
來查看Swagger UI。Swagger UI為你的API提供了一個交互式的用戶界面,使得調用者可以無需編寫代碼就能測試API的各個端點。
維護和更新Swagger文檔
遵循良好的文檔編寫實踐,確保每次API更新時,都同步更新相應的Swagger注釋。這有助于保持文檔的準確性和有效性。
小結
通過使用Swagger,開發(fā)者可以有效地設計和文檔化REST API,提高API的可讀性和可維護性,同時為其他開發(fā)者、前端團隊和API消費者提供一個清晰和準確的API參考。掌握上述技巧可以更好地利用Swagger來優(yōu)化后端API服務器的開發(fā)流程。
實例1:express & swagger
從創(chuàng)建一個新的Express應用程序開始:
npm init -y npm install express --save
編寫Express服務器并加入Swagger文檔。
步驟1:創(chuàng)建Express服務器
index.js
:
const express = require('express'); const swaggerJSDoc = require('swagger-jsdoc'); const swaggerUi = require('swagger-ui-express'); // 初始化express應用 const app = express(); const port = 3000; // 定義swagger文檔配置 const swaggerOptions = { swaggerDefinition: { openapi: '3.0.0', info: { title: '示例API', version: '1.0.0', description: '這是一個簡單的Express API應用示例', }, servers: [ { url: 'http://localhost:3000', description: '本地開發(fā)服務器', }, ], }, apis: ['./routes/*.js'], // 使用Glob模式指定API文件位置 }; // 初始化swagger-jsdoc const swaggerDocs = swaggerJSDoc(swaggerOptions); // 提供Swagger的UI界面 app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs)); // 定義一個簡單的路由處理函數 app.get('/', (req, res) => { res.send('歡迎使用示例API'); }); // 監(jiān)聽指定的端口 app.listen(port, () => { console.log(`服務器正在監(jiān)聽 http://localhost:${port}`); });
步驟2:創(chuàng)建路由并添加Swagger注釋
假設有一個用戶相關的API,為此創(chuàng)建一個處理用戶請求的路由文件。
routes/users.js
:
/** * @swagger * /users: * get: * tags: * - 用戶 * summary: 獲取用戶列表 * description: 請求所有注冊用戶信息 * responses: * 200: * description: 請求成功返回用戶列表 * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/User' * * components: * schemas: * User: * type: object * properties: * id: * type: integer * format: int64 * description: 用戶的唯一標識符 * name: * type: string * description: 用戶的姓名 * email: * type: string * format: email * description: 用戶的郵件地址 */ const express = require('express'); const router = express.Router(); // GET請求 - 獲取用戶列表 router.get('/', (req, res) => { // 模擬一些用戶數據 const users = [ { id: 1, name: '張三', email: 'zhangsan@example.com' }, { id: 2, name: '李四', email: 'lisi@example.com' }, ]; res.json(users); }); module.exports = router;
將此路由文件添加到Express應用中:
修改index.js
并在頂部添加以下內容:
const userRoutes = require('./routes/users');
然后,在index.js
中的Swagger UI代碼下面,添加以下代碼,以將用戶路由掛載到Express應用:
app.use('/users', userRoutes);
運行Express服務器并訪問http://localhost:3000/api-docs
時,將看到帶有用戶路由的Swagger UI界面,這個界面提供了一個交互式的API文檔。
如此一來就為Express API路由創(chuàng)建了Swagger文檔。通過添加更多路由和適當的Swagger注釋,可以繼續(xù)為其他API端點拓展文檔。
示例2:koa & swagger
如果使用的是Koa.js框架而非Express.js,依然可以使用Swagger來生成API文檔,但是整合方式會有所不同,因為Koa的中間件機制和Express略有差異。這里以koa
和koa-router
為例來實現增加Swagger文檔的步驟。
步驟1:創(chuàng)建Koa服務器
首先,安裝Koa相關的依賴:
npm init -y npm install koa koa-router --save
接下來,安裝Swagger相關的依賴:
npm install koa-swagger-decorator --save
然后,創(chuàng)建Koa服務器和路由:
index.js
:
const Koa = require('koa'); const Router = require('koa-router'); const { swagger, swaggerRouter } = require('./swagger'); const app = new Koa(); const router = new Router(); // 在路由中定義一個簡單的GET請求處理 router.get('/', async (ctx) => { ctx.body = '歡迎使用示例API'; }); // 將Swagger路由裝載到Koa應用 swaggerRouter(app); // 裝載所有路由子項 app.use(router.routes()).use(router.allowedMethods()); const port = 3000; app.listen(port, () => { console.log(`服務器運行在 http://localhost:${port}`); });
步驟2:配置Swagger文檔并為路由添加注解
創(chuàng)建Swagger配置文件:
swagger.js
:
const { SwaggerRouter } = require('koa-swagger-decorator'); const swaggerRouter = new SwaggerRouter(); // Swagger配置信息 swaggerRouter.swagger({ title: 'Koa 示例API', description: 'API文檔', version: '1.0.0', // swagger文檔頁面的訪問路徑 swaggerHtmlEndpoint: '/swagger-html', // swagger文檔的json訪問路徑 swaggerJsonEndpoint: '/swagger-json', // API服務器信息 swaggerOptions: { host: 'localhost:3000', }, }); // 在這里可以批量加入路由定義或一個個添加 // swaggerRouter.mapDir(__dirname); module.exports = { swagger: swaggerRouter.swagger.bind(swaggerRouter), swaggerRouter: swaggerRouter.routes.bind(swaggerRouter), };
添加路由和Swagger注解:
users.js
:
const { request, summary, query, tags } = require('koa-swagger-decorator'); const router = require('koa-router')(); // 定義tag const tag = tags(['用戶']); // 用戶路由的Swagger注解 router.get('/users', tag, summary('獲取用戶列表'), query({ name: { type: 'string', required: false, description: '按姓名查詢' } }), async (ctx) => { // 這里可以根據name來獲取用戶信息 // 為了示例使用靜態(tài)數據 const users = [ { id: 1, name: '張三' }, { id: 2, name: '李四' }, ]; ctx.body = { code: 0, data: users }; }); module.exports = router;
將此路由注解文件添加到Koa應用中,方法是在index.js
中添加下面的代碼:
const userApi = require('./users'); swaggerRouter.use(userApi.routes());
注意:確保在代碼中按自己實際的文件結構引入合適的路徑。
以上代碼將一個簡單的Koa應用轉換為使用koa-swagger-decorator
來生成swagger文檔。啟動該應用程序后,訪問http://localhost:3000/swagger-html
即可看到Swagger UI。
示例3:Egg & swagger
如果使用的是Egg.js框架,并希望集成Swagger來生成API文檔,則需要使用一些與Egg.js兼容的插件。Egg.js是基于Koa.js的更高層的框架,它有自己的插件系統(tǒng)。下面的舉例將展示如何使用egg-swagger-doc
這個Egg.js插件為API生成Swagger文檔。
步驟1:安裝egg-swagger-doc插件
首先,在Egg.js項目中安裝egg-swagger-doc
插件:
npm install egg-swagger-doc --save
步驟2:啟用插件
在Egg.js的配置文件中啟用Swagger文檔插件。通常會在config/plugin.js
中啟用:
// config/plugin.js exports.swaggerdoc = { enable: true, // 啟用swagger-ui插件 package: 'egg-swagger-doc', };
步驟3:配置Swagger插件
配置Swagger插件通常在config/config.default.js
中進行:
// config/config.default.js module.exports = (appInfo) => { const config = {}; // ... 其他配置 ... // 配置egg-swagger-doc config.swaggerdoc = { dirScanner: './app/controller', // 配置自動掃描的控制器路徑 apiInfo: { title: 'Egg.js API', // API文檔的標題 description: 'Swagger API for Egg.js', // API文檔描述 version: '1.0.0', // 版本號 }, schemes: ['http', 'https'], // 配置支持的協(xié)議 consumes: ['application/json'], // 指定處理請求的提交內容類型 (Content-Type),如 application/json, text/html produces: ['application/json'], // 指定返回的內容類型 securityDefinitions: { // 配置API安全授權方式 // e.g. apikey (下面是一些例子,需要自行定制) // apikey: { // type: 'apiKey', // name: 'clientkey', // in: 'header', // }, // oauth2: { // type: 'oauth2', // tokenUrl: 'http://petstore.swagger.io/oauth/dialog', // flow: 'password', // scopes: { // 'write:access_token': 'write access_token', // 'read:access_token': 'read access_token', // }, // }, }, enableSecurity: false, // enableValidate: true, // 是否啟用參數校驗插件,默認為true routerMap: false, // 是否啟用自動生成路由,默認為true enable: true, // 默認啟動swagger-ui }; return config; };
步驟4:使用JSDoc注釋編寫控制器代碼
在Egg.js控制器文件app/controller/home.js
中,用JSDoc注釋定義API:
'use strict'; const Controller = require('egg').Controller; /** * @controller Home API接口 */ class HomeController extends Controller { /** * @summary 首頁 * @description 獲取首頁信息 * @router get / 這里對應路由 * @request query string name 名字 * @response 200 baseResponse 返回結果 */ async index() { const { ctx } = this; ctx.body = `hello, ${ctx.query.name}`; } } module.exports = HomeController;
這里利用了egg-swagger-doc
所支持的JSDoc注解,定義了一個對應GET /
的API。
步驟5:啟動Egg.js應用并訪問Swagger文檔
啟動Egg.js應用:
npm run dev
在瀏覽器中訪問http://localhost:7001/swagger-ui.html
(默認Egg.js應用的端口是7001)查看Swagger文檔。
這就完成了在基于Egg.js框架的項目中集成Swagger文檔的步驟。以上是一個簡單的例子,實際開發(fā)中可能需要根據自己的業(yè)務需求進行相應的配置和編寫。通過集成Swagger,所開發(fā)的Egg.js應用將獲得一個自動化、易于閱讀和管理的API文檔。
以上就是Node.js中Swagger的使用指南詳解的詳細內容,更多關于Node.js Swagger的資料請關注腳本之家其它相關文章!
相關文章
node.js中的querystring.parse方法使用說明
這篇文章主要介紹了node.js中的querystring.parse方法使用說明,本文介紹了querystring.parse的方法說明、語法、接收參數、使用實例和實現源碼,需要的朋友可以參考下2014-12-12