You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求问:是否有工具可从Django/DRF代码生成API Blueprint(Apiary)文档

从Django/DRF代码生成API Blueprint的可行方案

当然有办法搞定这个需求!下面我给你分享几个实用的库和具体实现例子,帮你自动生成Apiary格式的API Blueprint文档。

1. 使用django-api-blueprint专用库

这个库是专门针对Django和DRF设计的,能直接从你的视图、序列化器和路由中提取核心信息,生成标准的API Blueprint文档。

安装步骤

pip install django-api-blueprint

配置与生成

  1. 先在项目的settings.py中添加该应用:
INSTALLED_APPS = [
    # 你的其他应用
    'django_api_blueprint',
]
  1. 在项目根目录下执行生成命令:
python manage.py generate_api_blueprint --output api_docs.md

这条命令会自动扫描项目中所有DRF的API视图,提取路径、请求方法、参数结构、响应格式等信息,直接生成完整的API Blueprint文档。

2. 结合DRF自省+apiblueprint自定义生成

如果需要更灵活的控制(比如自定义文档描述、添加权限说明等),可以利用DRF自带的视图自省能力,配合apiblueprint库手动构建文档内容。

安装依赖

pip install apiblueprint djangorestframework

示例脚本

创建一个generate_api_docs.py脚本:

from apiblueprint import APIBlueprint, Resource, Action, Response
from django.conf import settings
from django.urls import get_resolver
from rest_framework.views import APIView

# 初始化API Blueprint实例
api = APIBlueprint(title="我的DRF项目API", description="基于Django Rest Framework的全量API文档")

# 遍历项目中所有DRF视图
for url_pattern in get_resolver(None).url_patterns:
    # 判断是否为DRF视图类
    if hasattr(url_pattern.callback, 'view_class') and issubclass(url_pattern.callback.view_class, APIView):
        view_cls = url_pattern.callback.view_class
        # 提取路由路径(清理正则符号)
        path = url_pattern.pattern.regex.pattern.replace('^', '').replace('$', '')
        # 创建API资源
        resource = Resource(path)
        
        # 处理GET请求逻辑
        if hasattr(view_cls, 'get'):
            get_action = Action('GET', description="获取资源列表或详情")
            # 从序列化器提取响应结构
            if hasattr(view_cls, 'serializer_class'):
                serializer = view_cls.serializer_class()
                response_schema = serializer.data
                get_action.add_response(Response(200, description="请求成功", body=response_schema))
            resource.add_action(get_action)
        
        # 可按需扩展POST/PUT/DELETE等请求方法的处理逻辑...
        
        api.add_resource(resource)

# 保存生成的API Blueprint文档
with open('custom_api_docs.md', 'w', encoding='utf-8') as f:
    f.write(api.to_markdown())

运行脚本生成文档:

python generate_api_docs.py

3. 从OpenAPI转换为API Blueprint

如果你的项目已经在用drf-yasg或drf-spectacular生成OpenAPI文档,也可以通过转换工具快速转为Apiary支持的API Blueprint格式。

操作步骤

# 1. 安装转换工具(需先安装Node.js)
npm install -g swagger2apiblueprint

# 2. 用DRF工具生成OpenAPI的swagger.json文件
python manage.py generate_swagger -o swagger.json

# 3. 转换为API Blueprint格式
swagger2apiblueprint swagger.json > converted_api_docs.md

这个方案适合已经有OpenAPI文档存量的项目,无需额外改造代码就能完成格式转换。


内容的提问来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:17:33