django-rest-swagger 使用【轉】

轉自:http://www.javashuo.com/article/p-coxuljbg-gc.htmlhtml

Swagger是一個API開發者的工具框架,用於生成、描述、調用和可視化RESTful風格的Web服務。整體目標是使客戶端和文件系統服務器以一樣的速度來更新,方法,參數和模型緊密集成到服務器端的代碼中,容許API始終保持同步。git

在使用 django-rest-framework 進行API開發,能夠使用django-rest-swagger接入swagger自動生成接口文檔。github

1. 安裝django-rest-swaggerdjango

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.pypost

複製代碼
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/,能夠看到如下內容:url

 

訪問 http://127.0.0.1:8000/docs/,能夠看到接口文檔以下:

 

 點擊打開snippets,能夠看到以下,每一個方法後面都有你在views.py中添加的註釋

點擊打開get方法,以下

相關文章
相關標籤/搜索