参考文档: https://github.com/axnsan12/drf-yasg
安装
pip install drf_yasg
在settings.py中注册:
INSTALLED_APPS = [
'django.contrib.staticfiles',
# swagger
'drf_yasg',
]
在urls.py中配置路由:
from django.contrib import admin
from django.urls import path, include, re_path
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions
# swagger API文档配置 https://github.com/axnsan12/drf-yasg
schema_view = get_schema_view(
openapi.Info(
title="DRF Admin API",
default_version='v1.0.0',
description="Test Description",
terms_of_service="https://github.com/yejian12345",
contact=openapi.Contact(email="1591273646@qq.com"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
base_api = 'api/'
# swagger(API文档)
urlpatterns = [
path('admin/', admin.site.urls),
re_path(rf'^{base_api}swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
path(f'^{base_api}swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path(f'^{base_api}redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]
最后在settings.py中配置swagger
# Swagger接口文档配置
SWAGGER_SETTINGS = {
'USE_SESSION_AUTH': False,
'SECURITY_DEFINITIONS': {
'api_key': {
'type': 'apiKey',
'in': 'header',
'name': 'Authorization'
}
},
}