以下是在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
等類型。參考來源: