drf_yasg
- 作用: 自动 && 自定义 生成API文档
- 简单示例(自动生成)
### settings.py
INSTALLED_APPS = [
...
'rest_framework',
'drf_yasg',
]
### models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()
def __str__(self):
return self.title
### serializers.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['id', 'title', 'author', 'publication_date']
### views.py
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
### urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = [
path('', include(router.urls)),
]
- 在项目的主 urls.py 文件中添加 Swagger 文档的 URL 配置
# urls.py
from django.contrib import admin
from django.urls import path, include
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework import permissions
schema_view = get_schema_view(
# 配置文档的各种信息
openapi.Info(
title="Backend API",
default_version='v1',
description="API for managing",
terms_of_service="https://www.example.com/policies/terms/",
contact=openapi.Contact(email="contact@example.com"),
license=openapi.License(name="BSD License"),
),
# 该API文档视图是公开的
public=True,
# 任何人都可以访问该API文档视图
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('your_app_name.urls')),
# 有两个文档地址,区别在于不同的UI风格
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]
- 测试网址: http://localhost:8000/swagger/
http://localhost:8000/redoc/
### views(手动生成描述信息)
from .models import Departments
from .serializers import DepartmentsSerializer
from rest_framework import viewsets
# 导入函数
from drf_yasg.utils import swagger_auto_schema
class DepartmentsModelViewSet(viewsets.ModelViewSet):
queryset = Departments.objects.all()
serializer_class = DepartmentsSerializer
@swagger_auto_schema(
operation_description="获取所有部门列表",
operation_summary="获取部门列表",
tags=['部门管理'],
manual_parameters=[
openapi.Parameter('name', openapi.IN_QUERY, description="部门名称", type=openapi.TYPE_STRING),
],
responses={200: DepartmentsSerializer(many=True)},
)
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
@swagger_auto_schema(
operation_description="创建部门",
operation_summary="创建部门",
tags=['部门管理'],
# 请求体
request_body=DepartmentsSerializer,
# 响应体
responses={200: DepartmentsSerializer},
)
def create(self, request, *args, **kwargs):
return super().create(request, *args, **kwargs)