使用drf_yasg.openapi为DjangoRestFramework项目自动生成中文接口文档
发布时间:2023-12-27 02:45:50
在Django Rest Framework中使用drf_yasg(Yet Another Swagger Generator)可以方便地自动生成API接口文档。drf_yasg是一个基于OpenAPI规范(以前称为Swagger)的库,它提供了用于定义和生成API文档的工具。
下面是一个简单的Django Rest Framework项目的使用例子:
1. 首先,确保已经安装了drf_yasg和Django Rest Framework:
pip install drf-yasg pip install djangorestframework
2. 在Django项目的settings.py文件中添加以下配置:
INSTALLED_APPS = [
...
'rest_framework',
'drf_yasg',
...
]
SWAGGER_SETTINGS = {
'USE_SESSION_AUTH': False, # 不使用SessionAuthentication
'SECURITY_DEFINITIONS': {
"Token": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
},
},
}
3. 在项目的urls.py文件中添加swagger的url:
from django.conf.urls import url
from django.urls import include
from rest_framework.documentation import include_docs_urls
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="Django Rest Framework项目的API接口文档",
terms_of_service="https://www.example.com/policies/terms/",
contact=openapi.Contact(email="contact@example.com"),
license=openapi.License(name="BSD License"),
),
public=True,
)
urlpatterns = [
...
url(r'^api/v1/docs/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^api/v1/redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
...
]
上面的代码中定义了两个URL,用于访问Swagger UI和ReDoc UI。
4. 在项目的views.py文件中定义API视图:
from rest_framework import generics
from app.models import User
from app.serializers import UserSerializer
class UserListAPIView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetailAPIView(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
5. 在项目的serializers.py文件中定义序列化器:
from rest_framework import serializers
from app.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
6. 在项目的urls.py文件中配置API路径:
from django.urls import path
from app.views import UserListAPIView, UserDetailAPIView
urlpatterns = [
path('users/', UserListAPIView.as_view(), name='user_list'),
path('users/<int:pk>/', UserDetailAPIView.as_view(), name='user_detail'),
]
上面的代码配置了两个API路径,分别用于获取用户列表和获取特定用户的详细信息。
7. 运行Django服务器:
python manage.py runserver
8. 打开浏览器,访问Swagger UI的URL(如http://localhost:8000/api/v1/docs/),即可看到自动生成的API接口文档。
使用drf_yasg生成API接口文档非常简单,只需要按照上述步骤配置好即可。生成的文档包含了API的详细信息、输入输出参数以及示例请求和响应数据,方便开发者查阅和测试接口。
