温馨提示×

Debian系统Swagger文档编写指南

小樊
53
2025-08-11 20:35:19
栏目: 智能运维

以下是在Debian系统上编写Swagger文档的指南:

  1. 安装工具

    • 基于Node.js的项目:
      sudo apt update sudo apt install nodejs npm sudo npm install -g swagger-jsdoc swagger-ui-express 
    • 基于Python的项目(如Flask):
      pip install flasgger 
  2. 创建配置文件

    • 命名为swagger.jsonswagger.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" } } } } } 
  3. 集成到应用

    • Node.js(Express)
      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') ); 
    • Python(Flask)
      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' } }) 
  4. 生成与访问文档

    • 直接通过配置文件生成交互式文档,访问路径通常为http://localhost:端口号/api-docs
    • 如需生成静态文档,可使用swagger-jsdoc命令行工具:
      swagger-jsdoc -i ./swagger.json -o ./docs/output.json 
  5. 注意事项

    • 遵循OpenAPI规范,使用标准字段(如pathsdefinitionsresponses)。
    • 参数命名需清晰,支持querypathbody等类型。
    • 定期更新文档以匹配代码变更。

参考来源:

0