DRF automatically generates interface documents coreapi and DRF yasg

Time:2021-9-17

Rest framework can automatically help us generate interface documents.

Interface documents are presented as web pages.

Automatic interface documents can be generated by inheriting fromAPIViewAnd its subclasses.

1. Installation dependency

Rest framewrok needs to generate interface documentscoreapiLibrary support.

pip install coreapi

2. Set access path of interface document

Add the interface document path to the general route.

The view corresponding to the document route is configured asrest_framework.documentation.include_docs_urls

parametertitleIs the title of the interface document website.

from rest_framework.documentation import include_docs_urls

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

3. Definition location of document description

1) For a single method view, you can directly use the document string of the class view, such as

class BookListView(generics.ListAPIView):
    """
    Returns all book information
    """

2) For a view containing multiple methods, separate the method definitions in the document string of the class view, such as

class BookListCreateView(generics.ListCreateAPIView):
    """
    get:
    Returns all book information

    post:
    Create a new book
    """

3) For the view set viewset, it is still defined separately in the document string of the class view, but it should be distinguished by the action name, such as

class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    """
    list:
    Return book list data

    retrieve:
    Return book details data

    latest:
    Returns the latest book data

    read:
    Modify the reading volume of books
    """

4. Access interface document web page

Visit 127.0.0.1:8000 / docs / in the browser to see the automatically generated interface document.

Two points:

1) The retrieve name in the viewset of the view set is called read in the interface document website

2) The description of the parameter needs help in the field of the model class or serializer class_ Text option definition, such as:

class BookInfo(models.Model):
    ...
    Bread = models. Integerfield (default = 0, verbose_name = 'reading amount', help_text = 'reading amount')
    ...

or

class BookReadSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = ('bread', )
        extra_kwargs = {
            'bread': {
                'required': True,
                'help_ Text ':' reading quantity '
            }
        }

Second interface document

drf-yasg

#Installation
pip install drf-yasg

#Add to
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 = "interface document platform", # required
        default_ Version ='v1 ', # required
        Description = "document description",
        terms_of_service='',
        contact=openapi.Contact(email="[email protected]"),
        license=openapi.License(name="BSD LICENSE")
    ),
    public=True,
    # permission_ Classes = (permissions.) # permission class
)

urlpatterns += [
    # re_path(r'^swagger(?P\.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'),
]