DRF 框架之 API文档 Swagger配置

这篇博客介绍了如何在Django REST Framework项目中集成drf-yasg库,通过简单配置settings.py和urls.py文件,生成Swagger UI和Redoc接口文档,以提供API的可视化描述和测试功能。设置包括安装库、注册应用、配置路由以及Swagger接口文档的定制。这有助于开发者更好地管理和理解API接口。
摘要由CSDN通过智能技术生成

参考文档: 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'
        }
    },
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值