在Python中使用drf_yasg.openapi来生成规范的RESTfulAPI文档
发布时间:2023-12-28 04:43:27
在Python中,可以使用drf_yasg.openapi包来生成规范的RESTful API文档。drf_yasg.openapi是一个Django REST framework (DRF)的扩展,可以自动生成规范的API文档,包括路径、请求方法、参数、响应等信息,并支持使用例子来说明API的使用方法。
下面是一个使用drf_yasg.openapi生成API文档的例子:
首先,安装drf_yasg和Swagger UI。
pip install drf_yasg pip install django-filter pip install -U drf-yasg[validation]
在Django的settings.py文件中添加drf_yasg和rest_framework的配置:
INSTALLED_APPS = [
...
'drf_yasg',
'rest_framework',
...
]
REST_FRAMEWORK = {
...
'DEFAULT_SCHEMA_CLASS': 'drf_yasg.openapi.AutoSchema',
...
}
在Django的urls.py文件中添加API文档的路由:
from django.urls import include, path
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
router = routers.DefaultRouter()
schema_view = get_schema_view(
openapi.Info(
title='API 文档',
default_version='v1',
description='API 文档',
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
path('', include(router.urls)),
path('api/', include('api.urls')),
path('api/auth/', obtain_auth_token, name='api-token-auth'),
path('api/doc/', schema_view.with_ui('swagger', cache_timeout=0), name='api-doc'),
]
在Django的api/views.py文件中添加API的示例视图:
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def hello(request):
"""
示例 API
查询参数:
- name: 名称
返回结果示例:
{
"message": "Hello, {name}!"
}
"""
name = request.query_params.get('name', 'World')
return Response({'message': f'Hello, {name}!'})
最后,在Swagger UI中访问API文档:
http://localhost:8000/api/doc/
在Swagger UI中,可以看到生成的API文档,包括示例API和参数等信息。用户可以通过Swagger UI中提供的界面进行API的测试和调试。
通过使用drf_yasg.openapi包,可以方便地生成规范的RESTful API文档,并且支持使用例子来展示API的使用方法,帮助开发者更好地理解和使用API。
