介绍
REST framework可以自动帮助我们生成接口文档。
接口文档以网页的方式呈现。
自动接口文档能生成的是 继承自APIView
及其子类 的视图。
操作
安装依赖包
pip install coreapi
settings.py
INSTALLED_APPS = [
....
'rest_framework',
]
在总路由中添加接口文档路径
参数title:
为接口文档网站的标题
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
url(r'^docs/', include_docs_urls(title='API接口文档'))
]
文档描述说明的定义位置
视图
包含多个方法的视图,在类视图的文档字符串中,分开方法定义,如
class BookListCreateView(generics.ListCreateAPIView):
"""
get:
返回所有图书信息.
post:
新建图书.
"""
视图集
对于视图集ViewSet,仍在类视图的文档字符串中分开定义,但是应使用action名称区分
class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
"""
list:
返回图书列表数据
retrieve:
返回图书详情数据
latest:
返回最新的图书数据
read:
修改图书的阅读量
"""
访问
浏览器访问 127.0.0.1:8000/docs/,即可看到自动生成的接口文档
注意
1. 视图集ViewSet中的retrieve名称,在接口文档网站中叫做read
2. 参数,的Description(描述说明)需要在模型类或序列化器类的字段中以help_text选项定义
class BookInfo(models.Model):
...
readcount= models.IntegerField(default=0, verbose_name='阅读量', help_text='阅读量')
...
或者
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = BookInfo
fields = '__all__'
extra_kwargs = {
'readcount':{
'help_text':'阅读量' # 即,对该字段的说明描述
}
}