1. 程式人生 > 程式設計 >django-rest-swagger對API介面註釋的方法

django-rest-swagger對API介面註釋的方法

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/,可以看到以下內容:

訪問 http://127.0.0.1:8000/docs/,可以看到介面文件如下:

點選開啟snippets,可以看到如下,每個方法後面都有你在views.py中新增的註釋

點選開啟get方法,如下

以上這篇django-rest-swagger對API介面註釋的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。