以下是在Debian系统上编写Swagger文档的指南:
安装工具
sudo apt update sudo apt install nodejs npm sudo npm install -g swagger-jsdoc swagger-ui-express
pip install flasgger
创建配置文件
swagger.json
或swagger.yaml
,定义API元数据:{ "swagger": "2.0", "info": { "title": "API文档", "version": "1.0.0", "description": "API功能描述" }, "basePath": "/api", "paths": { "/users": { "get": { "summary": "获取用户列表", "responses": { "200": { "description": "成功返回用户列表", "schema": { "type": "array", "items": { "$ref": "#/definitions/User" } } } } } } }, "definitions": { "User": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" } } } } }
集成到应用
const express = require('express'); const swaggerUi = require('swagger-ui-express'); const swaggerDocument = require('./swagger.json'); const app = express(); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); app.listen(3000, () => console.log('服务已启动,访问 http://localhost:3000/api-docs') );
from flasgger import Swagger from flask import Flask app = Flask(__name__) Swagger(app, config={ 'swagger_ui_bundle_js': 'https://rawcdn.githack.com/swagger-api/swagger-ui/v3.23.0/dist/swagger-ui-bundle.js', 'openapi': '3.0.0', 'info': { 'title': 'API文档', 'version': '1.0.0' } })
生成与访问文档
http://localhost:端口号/api-docs
。swagger-jsdoc
命令行工具:swagger-jsdoc -i ./swagger.json -o ./docs/output.json
注意事项
paths
、definitions
、responses
)。query
、path
、body
等类型。参考来源: