Flask API 文档化指南 (Flasgger)

Flask API 文档化指南 (Flasgger)

本文档详细说明本项目中如何使用 Flasgger 进行 API 文档的自动生成与管理。

1. 快速入门

Flasgger 是一个 Flask 扩展,它能从你的代码注释 (Docstrings) 或单独的 YAML 文件中提取信息,自动生成标准的 Swagger UI 文档页面。

访问地址: 启动项目后,访问 http://localhost:5000/apidocs/


2. 安装与注册 (Initialization)

2.1 依赖安装

requirements.txt 中包含:

flasgger==0.9.5 # 或其他版本

2.2 注册位置

app/__init__.py 的工厂函数中进行初始化:

from flasgger import Swagger
def create_app():
app = Flask(__name__)
# 1. 定义整体文档的元数据
template = {
"swagger": "2.0",
"info": {
"title": "OakAMC API",
"description": "API Documentation",
"version": "0.1.0"
},
# 定义鉴权方式 (如 Bearer Token)
"securityDefinitions": {
"ApiKeyAuth": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
}
}
# 2. 绑定到 App
Swagger(app, template=template)

3. 使用方式详解

本项目主要采用 YAML 文件分离模式,让代码更干净。

3.1 核心装饰器 @swag_from

语法:

from flasgger import swag_from
@bp.route('/users')
@swag_from('specs/get_users.yml') # <--- 引用 YAML 文件
def get_users():
pass

3.2 路径解析规则 (Path Resolution)

这是一个常见的坑点:@swag_from 的路径到底是相对于谁?

  • 规则: 它是 相对于当前 Python 文件 (routes.py) 的。
  • 示例:
    • 代码文件: app/modules/product_mgmt/securities_account/routes.py
    • 引用路径: @swag_from('specs/fetch_list.yml')
    • 实际文件: app/modules/product_mgmt/securities_account/specs/fetch_list.yml

最佳实践: 在每个 routes.py 同级目录下创建一个 specs 文件夹,专门存放 YAML 文档。


4. YAML 编写语法 (Swagger 2.0)

一个标准的 YAML 文档结构如下:

# 1. 接口描述
tags:
- ProductMgmt # 接口分类/标签
summary: 查询证券账户列表
description: 分页查询证券账户信息,支持多条件筛选
parameters:
# 2.1 路径参数 (Path Parameters) —— in的值为path
- name: page
in: path
type: integer
required: true
description: 页码
- name: limit
in: path
type: integer
required: true
description: 每页条数
# 2.2 表单参数 (Form Data / Body) —— in的值为formData
- name: securitiesAccountName
in: formData
type: string
required: false
description: 证券账户名称(模糊查询)
# 3. 响应定义 (Responses)
responses:
200:
description: 查询成功
schema:
# 引用预定义的模型(如果有)或直接写结构
type: object
properties:
code:
type: integer
example: 200
data:
type: object
properties:
items:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string

Docstring 模式 (备选)

如果不使用 @swag_from,也可以直接写在函数注释里(适合简单接口),---之下的就是flasgger内容:

def my_api():
"""
My API Summary
---
tags:
- MyTag
responses:
200:
description: OK
"""
pass

5. 常见问题配置

5.1 鉴权 (Authentication)

如果在 __init__.py 中定义了 securityDefinitions,在 YAML 中需要显式开启:

security:
- ApiKeyAuth: []

这样 Swagger UI 上会出现一把小锁,点击并在 Value 框中输入 Bearer <token> 即可进行带 Token 调试。

5.2 参数位置 (in)

  • path: 路径参数,如 /users/{id}
  • query: 问号参数,如 /users?id=1
  • formData: 表单提交 (application/x-www-form-urlencoded)
  • body: JSON 提交 (application/json)
  • header: 请求头参数