REST framework可以自動幫助我們生成接口文檔。
接口文檔以網頁的方式呈現。
自動接口文檔能生成的是繼承自APIView
及其子類的視圖。
安裝依賴
REST framewrok生成接口文檔需要coreapi
庫的支持。
pip install coreapi
設置接口文檔訪問路徑
文檔路由對應的視圖配置為rest_framework.documentation.include_docs_urls
,
參數title
為接口文檔網站的標題。
from rest_framework.documentation import include_docs_urls urlpatterns = [ ... path('docs/', include_docs_urls(title='站點頁面標題')) ]
文檔描述說明的定義位置
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: 修改圖書的閱讀量 """
訪問接口文檔網頁
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 = BookInfo fields = ('bread', ) extra_kwargs = { 'bread': { 'required': True, 'help_text': '閱讀量' } }
注意 : 基於rese_framework序列化
接口文檔工具 : http://yapi.demo.qunar.com/