django-rest-swagger对API接口注释

时间:2022-06-30 03:15:36

Swagger是一个API开发者的工具框架,用于生成、描述、调用和可视化RESTful风格的Web服务。总体目标是使客户端和文件系统服务器以同样的速度来更新,方法,参数和模型紧密集成到服务器端的代码中,允许API始终保持同步。

在使用 django-rest-framework 进行API开发,可以使用django-rest-swagger接入swagger自动生成接口文档。

1. 安装django-rest-swagger

pip install django-rest-swagger

2.配置settings.py

INSTALLED_APPS = [
    ...

    'rest_framework_swagger'

    ...
]

3. views.py

该博文的项目是django-rest-framework中文站点的例子:https://q1mi.github.io/Django-REST-framework-documentation

当需要对接口的各种方法进行注释时,直接在该类下添加注释,如下所示。需要注意是的:注释的方法名称(如 get、post)要对应该类所含的方法名称

class SnippetList(generics.ListCreateAPIView):
    """
    get:
        Return all snippets.
    post:
        Create a new snippet instance.
    """

    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    get:
        Return a snippet instance.
    put:
        Update a snippet instance.
    patch:
        Update a snippet instance.
    delete:
        Delete a snippet instance.
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)


class UserList(generics.ListAPIView):
    """
    get:
        Return all users
    """
    queryset = MyUser.objects.all()
    serializer_class = UserSerializer


class UserDetail(generics.RetrieveAPIView):
    """
    get:
        Return a user instance
    """
    queryset = MyUser.objects.all()
    serializer_class = UserSerializer


class SnippetHighlight(generics.GenericAPIView):
    """
    get:
        Return a highlight instance
    """
    queryset = Snippet.objects.all()
    renderer_classes = (renderers.StaticHTMLRenderer,)

    def get(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

3.配置urls.py

from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPICodec
schema_view = get_schema_view(title='API', renderer_classes=[SwaggerUIRenderer, OpenAPICodec])

urlpatterns = [
    
    ...

    url(r'docs/', schema_view, name='docs')

    ...
]

运行manage.py后,浏览器访问 http://127.0.0.1:8000/,可以看到以下内容:

 django-rest-swagger对API接口注释

访问 http://127.0.0.1:8000/docs/,可以看到接口文档如下:

django-rest-swagger对API接口注释

 

 点击打开snippets,可以看到如下,每个方法后面都有你在views.py中添加的注释

django-rest-swagger对API接口注释

点击打开get方法,如下

django-rest-swagger对API接口注释