[
课程介绍](_index_)
[
引入DjangoRESTframework](c01-introducetodrf_index)-[Web应用模式](c01-introducetodrf_separatedfrontendandbackend)
[
认识RESTful](c01-introducetodrf_introducetorest)
[
RESTful设计方法](c01-introducetodrf_howtodesignrest)
[
使用Django开发REST接口](c01-introducetodrf_developrestapiwithdjango)
[
明确REST接口开发的核心任务](c01-introducetodrf_coretasktodeveloprestapi)
[
DjangoRESTframework简介](c01-introducetodrf_aboutdrf)
[
DRF工程搭建](c02-drfproject_index)-[环境安装与配置](c02-drfproject_installandconfig)
[
见识DRF的魅力](c02-drfproject_thefirstdrfprogram)
[
Serializer序列化器](c03-serializer_index)-[定义Serializer](c03-serializer_declaring)
[
序列化使用](c03-serializer_serializing)
[
反序列化使用](c03-serializer_deserializing)
[
模型类序列化器ModelSerializer](c03-serializer_modelserializer)
[
视图](c04-view_index)-[Request与Response](c04-view_requestandresponse)
[
视图概览](c04-view_view)
[
视图说明](c04-view_viewintroduction)
[
视图集ViewSet](c04-view_viewset)
[
路由Router](c04-view_routers)
[
其他功能](c05-components_index)-[认证](c05-components_authentication)
[
权限](c05-components_permissions)
[
限流](c05-components_throttling)
[
过滤](c05-components_filtering)
[
排序](c05-components_ordering)
[
分页](c05-components_pagination)
[
版本](c05-components_versioning)
[
异常处理](c05-components_exceptions)
[
自动生成接口文档](c05-components_documents)
[Published with GitBook](https://www.gitbook.com)
课程介绍
自动生成接口文档
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_urlsurlpatterns = [...url(r'^docs/', include_docs_urls(title='My API title'))]
3. 文档描述说明的定义位置
1) 单一方法的视图,可直接使用类视图的文档字符串,如
class BookListView(generics.ListAPIView):"""返回所有图书信息."""
2)包含多个方法的视图,在类视图的文档字符串中,分开方法定义,如
class BookListCreateView(generics.ListCreateAPIView):"""get:返回所有图书信息.post:新建图书."""
3)对于视图集ViewSet,仍在类视图的文档字符串中封开定义,但是应使用action名称区分,如
class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):"""list:返回图书列表数据retrieve:返回图书详情数据latest:返回最新的图书数据read:修改图书的阅读量"""
4. 访问接口文档网页
浏览器访问 127.0.0.1:8000/docs/,即可看到自动生成的接口文档。
两点说明:
1) 视图集ViewSet中的retrieve名称,在接口文档网站中叫做read
2)参数的Description需要在模型类或序列化器类的字段中以help_text选项定义,如:
class BookInfo(models.Model):...bread = models.IntegerField(default=0, verbose_name='阅读量', help_text='阅读量')...
或
class BookReadSerializer(serializers.ModelSerializer):class Meta:model = BookInfofields = ('bread', )extra_kwargs = {'bread': {'required': True,'help_text': '阅读量'}}
