利用drf_yasg.openapi实现自动化生成API文档的方法与技巧
发布时间:2023-12-28 04:38:49
drf_yasg是一个用于自动化生成Django Rest Framework(DRF) API文档的工具。它提供了一个快速、简单和灵活的方式来生成规范的、易于理解的API文档。
首先,我们需要在项目中安装drf_yasg:
pip install drf_yasg
接下来,在Django项目的settings.py中进行配置,添加以下内容:
INSTALLED_APPS = [
...
'drf_yasg',
]
SWAGGER_SETTINGS = {
'DEFAULT_AUTO_SCHEMA_CLASS': 'drf_yasg.openapi.AutoSchema',
'DEFAULT_GENERATOR_CLASS': 'drf_yasg.generators.OpenAPISchemaGenerator',
'DEFAULT_INFO': 'your_project.urls.swagger_info',
'DEFAULT_FIELD_INSPECTORS': [
'drf_yasg.inspectors.CamelCaseJSONFilter',
'drf_yasg.inspectors.DjangoModelInspector',
'drf_yasg.inspectors.RelatedFieldInspector',
'drf_yasg.inspectors.PrimaryKeyRelatedFieldInspector',
'drf_yasg.inspectors.SerializerInspector',
'drf_yasg.inspectors.ChoiceFieldInspector',
'drf_yasg.inspectors.FileFieldInspector',
'drf_yasg.inspectors.DictFieldInspector',
'drf_yasg.inspectors.JSONFieldInspector',
'drf_yasg.inspectors.ManyRelatedFieldInspector',
'drf_yasg.inspectors.HiddenFieldInspector',
'drf_yasg.inspectors.ImageFieldInspector',
'drf_yasg.inspectors.IPAddressFieldInspector',
'drf_yasg.inspectors.ReadOnlyFieldInspector',
'drf_yasg.inspectors.RoutingFieldInspector',
'drf_yasg.inspectors.RoutingArgsInspector',
'drf_yasg.inspectors.SimpleFieldInspector',
'drf_yasg.inspectors.StringDefaultFieldInspector',
],
'DEFAULT_FILTER_INSPECTORS': [
'drf_yasg.inspectors.CoreAPICompatInspector',
'django_filters.rest_framework.DjangoFilterInspector',
'drf_yasg.inspectors.OASFilterInspector',
],
'DEFAULT_PAGINATOR_INSPECTORS': [
'drf_yasg.inspectors.CoreAPICompatInspector',
'drf_yasg.inspectors.OASFilterInspector',
],
'USE_SESSION_AUTH': False,
'OPERATIONS_SORTER': 'method',
'TAG_SORTER': 'alpha',
'DOC_EXPANSION': 'none',
'VALIDATOR_URL': None,
'VALIDATOR_URLS': [],
'SECURITY_DEFINITIONS': {
},
'DEFAULT_MODEL_DEPTH': 4,
'DEFAULT_MODEL_PARENT_LOOKUP': '__',
'CODE_SAMPLES': False,
'SECURITY': [],
'FAST_RESPONSE_LIMIT': 100
}
在urls.py中,添加以下内容:
from django.conf.urls import url
from django.urls import path
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="API文档",
default_version='v1',
description="API接口文档",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="contact@your_domain.com"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
path('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'),
]
这样配置完成后,我们就可以在/swagger/路径下访问自动生成的API文档了。
除了上述配置,我们还可以使用一些装饰器和字段描述器等功能来进一步定制生成的API文档。
例如,我们可以使用@swagger_auto_schema装饰器来自定义接口的文档描述,如下所示:
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
@swagger_auto_schema(
operation_description="获取用户信息",
responses={200: openapi.Response(description='OK', schema=UserSerializer)},
manual_parameters=[
openapi.Parameter(
name='id',
in_=openapi.IN_PATH,
type=openapi.TYPE_INTEGER,
description='用户ID',
),
],
)
@api_view(['GET'])
def get_user(request, id):
user = User.objects.get(id=id)
serializer = UserSerializer(user)
return Response(serializer.data)
上述代码中,我们使用swagger_auto_schema装饰器为get_user接口添加了操作的描述、响应的描述以及参数的描述。
另外,我们还可以使用@swagger_serializer_method和@swagger_auto_schema装饰器来定制序列化器的字段描述。
from drf_yasg.utils import swagger_auto_schema, swagger_serializer_method
class UserSerializer(serializers.ModelSerializer):
full_name = serializers.SerializerMethodField()
@swagger_serializer_method(serializer_or_field=UserSerializer)
def get_full_name(self, obj):
...
class Meta:
model = User
fields = ['id', 'full_name', 'email']
@swagger_auto_schema(
request_body=UserSerializer,
responses={201: openapi.Response(description='Created', schema=UserSerializer)},
)
@api_view(['POST'])
def create_user(request):
...
上述代码中,我们使用swagger_auto_schema装饰器为create_user接口添加了请求体的描述和响应的描述。
drf_yasg还支持其他一些功能,例如生成API的分组、版本控制、鉴权等。可以参考其官方文档了解更多详细的用法和配置。
总结来说,利用drf_yasg可以方便快速地生成规范的、易于理解的API文档。我们可以通过配置和使用装饰器等方式来进一步定制生成的API文档,以满足项目的需求。
