yarn add swagger-ui-express swagger-jsdoc
app.js
中添加上
// swagger
const swaggerUi = require('swagger-ui-express');
const swaggerJSDoc = require('swagger-jsdoc');
const app = express();
const swaggerJSDocOptions = {
definition: {
openapi: '3.0.0',
info: {
title: '长乐未央',
version: '1.0.0',
},
},
apis: ['./routes/*.js'], // 包含接口说明、注释的文件路径
};
const swaggerSpec = swaggerJSDoc(swaggerJSDocOptions);
const swaggerUiOptions = {
explorer: true
}
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, swaggerUiOptions));
找到你的接口文件,例如routes/articles
var express = require('express');
var router = express.Router();
var models = require('../models');
/**
* @swagger
*
* /articles/{articleId}:
* get:
* description: 查询单条记录
* security:
* - ApiKeyAuth: []
* tags:
* - 文章
* parameters:
* - name: articleId
* in: path
* required: true
* description: 文章的id
* default: 1
* schema:
* type: integer
* format: int64
* minimum: 1
* responses:
* '200':
* description: 返回的当前文章
* content:
* application/json:
* schema:
* type: object
* properties:
* id:
* type: integer
* example: 1
* title:
* type: string
* example: 明天可能下雨
* content:
* type: string
* example: 哈哈哈哈
* required:
* - id
* - name
* '404':
* description: 页面未找到
*
*/
router.get('/:id', async function (req, res, next) {
const article = await models.Article.findByPk(req.params.id);
res.json(article)
});
module.exports = router;
访问 http://localhost:3000/api-docs/
实测接口
已添加到喜欢了