溫馨提示×

Debian系統Swagger文檔編寫指南

小樊
45
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規范,使用標準字段(如paths、definitions、responses)。
    • 參數命名需清晰,支持query、path、body等類型。
    • 定期更新文檔以匹配代碼變更。

參考來源:

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女