debian

Debian Swagger在API设计中的应用案例

小樊
41
2025-08-05 17:04:09
栏目: 智能运维

以下是一个在Debian系统中使用Swagger进行API设计的简单案例:

环境准备

在Debian系统上安装必要的工具,如使用pip安装flaskflasgger

sudo apt update
sudo apt install python3-pip
pip3 install flask flasgger

定义API规范

创建一个Python文件,如app.py,并定义API规范:

from flask import Flask, jsonify
from flasgger import Swagger

app = Flask(__name__)

swagger_config = {
    'headers': [],
    'specs': [
        {
            'endpoint': 'apispec_1',
            'route': '/apispec_1.json',
            'rule_filter': lambda rule: True,
            'model_filter': lambda tag: True,
        }
    ],
    'static_url_path': '/flasgger_static',
    'swagger_ui': True,
    'specs_route': '/swagger/'
}

swagger = Swagger(app, config=swagger_config)

@app.route('/api/items/<int:item_id>')
def get_item(item_id):
    """
    Sample API endpoint to retrieve an item by ID
    ---
    tags:
      - items
    parameters:
      - in: path
        name: item_id
        type: integer
        required: true
        description: The ID of the item to retrieve
    responses:
      200:
        description: An example item
        schema:
          id: Item
          properties:
            id:
              type: integer
              format: int64
            name:
              type: string
    """
    return jsonify({"item_id": item_id, "name": "Sample Item"})

if __name__ == '__main__':
    app.run(debug=True)

运行与测试

运行应用:

python3 app.py

打开浏览器,访问http://<your-debian-server-ip>/swagger/,可看到Swagger UI界面,能查看和测试定义的API。

0
看了该问题的人还看了