前言
第三方库drf-yasg
(Django Rest Swagger)。它是一个为Django Rest Framework提供Swagger/OpenAPI规范支持的库。按照以下步骤进行操作:
安装
pip install drf-yasg -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
配置
1、在项目的settings.py
INSTALLED_APPS = [...'drf_yasg',... ]
2、在项目的urls.py
低于Django 3.1版本
from django.conf.urls import url from django.urls import include from drf_yasg import openapi from drf_yasg.views import get_schema_view# 配置Swagger文档 schema_view = get_schema_view(openapi.Info(title="API文档",default_version='v1',description="API文档描述",terms_of_service="https://www.example.com/terms/",contact=openapi.Contact(email="contact@example.com"),license=openapi.License(name="BSD License"),),public=True, )# Swagger文档路由 urlpatterns = [...url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),... ]
Django 3.1版本及更高版本
from django.urls import re_path from django.urls import include from drf_yasg import openapi from drf_yasg.views import get_schema_view# 配置Swagger文档 schema_view = get_schema_view(openapi.Info(title="API文档",default_version='v1',description="API文档描述",terms_of_service="https://www.example.com/terms/",contact=openapi.Contact(email="contact@example.com"),license=openapi.License(name="BSD License"),),public=True, )# Swagger文档路由 urlpatterns = [...re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),... ]
启动项目并查看效果
访问http://localhost:8000/swagger/
,您将能够看到自动生成的Swagger文档