DRF-自动生成接口文档

REST framework可以自动帮助我们生成接口文档。

接口文档以网页的方式呈现。

自动接口文档能生成的是继承自APIView及其子类的视图。

1. 安装依赖

REST framewrok生成接口文档需要coreapi库的支持

pip install coreapi

 

2. 设置接口文档访问路径

在总路由中添加接口文档路径。

文档路由对应的视图配置为rest_framework.documentation.include_docs_urls

参数title为接口文档网站的标题。

from rest_framework.documentation import include_docs_urls

urlpatterns = [
    ...
    url(r'^docs/', include_docs_urls(title='My REST API'))
]

 

3. 文档描述说明的定义位置

1) 单一方法的视图,可直接使用类视图的文档字符串,如

class DepartmentListView(generics.ListAPIView):
    """
    返回所有部门信息.
    """

2)包含多个方法的视图,在类视图的文档字符串中,分开方法定义,如

class DepartmentListCreateView(generics.ListCreateAPIView):
    """
    get:
    返回所有部门信息.

    post:
    创建部门.
    """

3)对于视图集ViewSet,仍在类视图的文档字符串中封开定义,但是应使用action名称区分,如

class DepartmentViewSet(ListModelMixin, RetrieveModelMixin, GenericViewSet):
    """
    list:
    分页查询部门对象

    retrieve:
    查询一个部门信息

    latest:
    查询最新添加的部门

    name:
    修改部门名称
    """

 

两点说明:

1) 视图集ViewSet中的retrieve名称,在接口文档网站中叫做 read

2)参数的Description需要在序列化器类的字段中以help_text选项定义,如:

class DepartmentSerializer(serializers.Serializer):
    ...
    name = serializers.CharField(label='部门名称', max_length=20,
        help_text='部门名称')
    ...
class DepartmentSerializer2(serializers.ModelSerializer):
    ...
    class Meta:
        ...
        extra_kwargs = {
            'name': {..., 'help_text': '部门名称'}
        }
posted @ 2018-11-12 16:37  苦瓜爆炒牛肉  阅读(2397)  评论(0编辑  收藏  举报