能否使用DRF-SPECTACULAR对接外部API?能否用JSON/YAML生成Swagger/Redoc文档?
DRF-Spectacular 相关问题解答
为独立应用编写API文档
如果你的独立应用已集成到Django项目中,按以下步骤即可生成专属API文档:
- 在应用目录下创建
schema.py,配置专属的spectacular视图:from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView class AppSpectacularAPIView(SpectacularAPIView): pass # 可自定义schema标识,用于区分不同应用的文档 class AppSpectacularSwaggerView(SpectacularSwaggerView): url_name = "your_app:schema" - 在应用的
urls.py中注册视图:from django.urls import path from .schema import AppSpectacularAPIView, AppSpectacularSwaggerView urlpatterns = [ path("schema/", AppSpectacularAPIView.as_view(), name="schema"), path("docs/", AppSpectacularSwaggerView.as_view(url_name="schema"), name="swagger-docs"), ] - 用
@extend_schema装饰器给应用内的视图/视图集添加文档元数据:from drf_spectacular.utils import extend_schema from rest_framework.views import APIView class YourAppAPIView(APIView): @extend_schema( summary="获取资源列表", responses={200: YourResponseSerializer}, ) def get(self, request): # 视图逻辑 pass - 确保项目配置中
INSTALLED_APPS包含drf_spectacular,并配置SPECTACULAR_SETTINGS的基础参数(如TITLE、VERSION)。
对接外部API
DRF-Spectacular支持手动将外部API整合到文档中,核心是手动编写符合OpenAPI规范的schema:
- 自定义
SchemaGenerator扩展路径:
然后在from drf_spectacular.generators import SchemaGenerator class CustomGenerator(SchemaGenerator): def get_paths(self, paths, view_classes): # 手动添加外部API的路径与schema定义 paths["/external/api/resource"] = { "get": { "summary": "外部API资源获取", "responses": { "200": { "description": "成功响应", "content": { "application/json": { "schema": {"type": "object", "properties": {"id": {"type": "integer"}}} } } } } } } return super().get_paths(paths, view_classes)SPECTACULAR_SETTINGS中指定GENERATOR_CLASS = "your.module.CustomGenerator"。 - 若只需关联外部文档链接,可在内部API视图上使用
@extend_schema(external_docs={"url": "https://external.api/docs", "description": "外部API文档"})。
从JSON/YAML文件生成Swagger/Redoc文档
完全可以,步骤如下:
- 导出OpenAPI schema文件
- 接口导出:访问项目的spectacular schema接口(如
/api/schema/?format=yaml),保存返回内容为schema.yml;或用/api/schema/获取JSON格式。 - 命令行导出:
python manage.py spectacular --file schema.json # 导出JSON python manage.py spectacular --file schema.yml # 导出YAML
- 接口导出:访问项目的spectacular schema接口(如
- 生成静态文档
- Swagger UI:下载Swagger UI静态资源包,修改
index.html中的url属性为本地schema文件路径(如url: "./schema.json"),直接打开index.html即可。 - Redoc:创建HTML文件引入Redoc CDN并指定schema路径:
打开该HTML文件即可渲染Redoc文档。<!DOCTYPE html> <html> <body> <redoc spec-url="./schema.yml"></redoc> <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script> </body> </html>
- Swagger UI:下载Swagger UI静态资源包,修改
内容的提问来源于stack exchange,提问作者jeffreyb
相关产品推荐
相关产品推荐

