DRF自动生成接口文档coreapi和drfyasg

DRF 自动生成接口文档 coreapi和drf-yasg[Python基础]

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 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 = BookInfo

fields = ("bread", )

extra_kwargs = {

"bread": {

"required": True,

"help_text": "阅读量"

}

}

第二种接口文档

drf-yasg

# 安装

pip install drf-yasg

# 添加到

INSTALLED_APPS = [

"drf_yasg",

]

from drf_yasg.views import get_schema_view

from drf_yasg import openapi

schema_view = get_schema_view(

openapi.Info(

title="接口文档平台", # 必传

default_version="v1", # 必传

description="文档描述",

terms_of_service="",

contact=openapi.Contact(email="1093254791@qq.com"),

license=openapi.License(name="BSD LICENSE")

),

public=True,

# permission_classes=(permissions.) # 权限类

)

urlpatterns += [

# re_path(r"^swagger(?P<format>.json|.yaml)$", schema_view.without_ui(cache_timeout=0)),

path("swagger/", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger"),

path("redoc/", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc"),

]

以上是 DRF自动生成接口文档coreapi和drfyasg 的全部内容, 来源链接: utcz.com/z/537622.html

回到顶部