[PYTHON] How to automatically generate API document with Django REST framework & POST from document screen

In this article, I will explain how to automatically generate the API document (explanation of usage etc.) when creating an API with Django REST framework.

Step 0: DRF (Django REST framework)

This time, I am using ** version: 3.10.3 **. The latest version (September 2020) is ** version: 3.11.1 **.

Step 1: Install additional packages

Install the packages required for automatic API documentation.

pip install coreapi
pip install Pygments
pip install Markdown

Step 2: Define a doc page in urls.py

For urls.py in the app folder that Django App is based on

from rest_framework.documentation import include_docs_urls

To enable the use of ʻinclude_docs_urls ()`.

After that, set path ("docs / "...) in the urls.py of the application as follows.

...

from rest_framework.documentation import include_docs_urls

urlpatterns = [
    path("admin/", admin.site.urls),
    path("docs/", include_docs_urls(title='API Document')),
    ...

Now, if you access / docs (for example, http: // localhost: 8000 / docs /), you will see the API documentation page as shown below.

api1.JPG

** * Error countermeasures ** When you visit the docs page, ʻautoschema'object has no attribute'get_link' django` If the error is displayed,

In the settingts.py of the application folder, as follows 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' Will be added.

...
REST_FRAMEWORK = {
    ...
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}

This happens if you are using DRF version 3.10 or higher.

(Reference) Django REST framework 3.10 https://www.django-rest-framework.org/community/3.10-announcement/

Step 3: How to read the doc screen

At the bottom left of the screen, there are menus called Authentication and Source Code.

[3.1] You can log in by deploying Authentication. If you log in here, you can hit the API from this doc screen while logged in. (How to hit the API will be explained in the later section).

[3.2] Source Code uses coreapi on the right side of the screen

You can display the implementation code for each API

api2.JPG

** * Error countermeasures ** If you go to the normal API screen instead of the doc screen for some reason, if you access docs / while logged in once from the Django Admin screen, the docs screen will be displayed (cause unknown).

Step 3: Prepare the API description

At the moment, there is no explanation of the operation for each API. (Since {id} is taken in the URL only for read, "id" is automatically described as a required parameter)

api3.JPG

Add a description of each API here.

If you write a comment for the "ViewSet class" that inherits viewssets.ViewSet etc. in views.py of the corresponding app, it will be reflected in docs as an API explanation.

For example, viewssets.ViewSet Since the API is divided into each class of list, create, retrieve, update, partial_update, destroy, Describe the API description for each of those classes.

The implementation is as follows.


class DatasetViewset(viewsets.ViewSet):
    """
    list:
Get information for all datasets.

    create:
Create new data set meta information.

    retrieve:
Get the information of the individual data set specified by pk.
   
    """

    def list(self, request):
・ ・ ・

Then, the description described as follows will be added to the docs of the API.

api4.JPG

In addition, when describing the API description, what kind of content should be described will be explained at the end of this article.

Step 4: Be able to hit the API

You can hit the API from this doc screen. If you click the green "Interact" button in the center of the above screen, the screen for hitting the API will appear.

This is fine for GET systems, but create (POST) and PUT systems are currently incomplete.

Also, in the previous figure, the parameters required for create and put are not described, which is insufficient as an explanation of the API.

Even if I click the "Interact" button of create, the screen as shown below is displayed and the parameter value to be POSTed cannot be written.

api5.JPG

There are various ways to arrange the explanation of this POST and PUT API so that you can hit the POST API.

The Django REST framework Schema is the explanation. https://www.django-rest-framework.org/api-guide/schemas/

One easy way is to def get_serializer(self): The code of is described in the ViewSet class, and for each method, It is a strategy to describe the serializer used in that method and divert it.

class DatasetViewset(viewsets.ViewSet):
    """
    list:
Get information for all datasets.

    create:
Create new data set meta information.

    retrieve:
Get the information of the individual data set specified by pk.
    """

    def get_serializer(self):
        """For API documentation"""
        if self.action is "create":
            return DatasetCreateInputSerializer()
        elif self.action is "update":
            return DatasetUpdateMetadataInputSerializer()

    def list(self, request):
・ ・ ・

Then, the doc screen changes as follows.

api6.JPG

The above figure is a little hard to see, but create and update have the parameters required for each API.

The last thing to worry about is that there is no description in the description of each parameter.

To describe the description properly to explain the arguments used in the API, go to models.py

name = models.CharField(blank=False, max_length=100, unique=True, help_text="Project name")

Describe the explanation in the argument "help_text" as in.

If you have created a model-independent class in serializers.Serializer in serializers, describe it in the argument "help_text" of that field.

Then, the doc screen will be as follows, and the description of each Parameter will be entered in the Description such as "Dataset name".

api7.JPG

And if it is in this state (def get_serializer () is described in ViewSet class and the serializer used in that method is specified for each method),

If you click the green "Interact" button in the center of the screen, the screen for hitting the API will appear with the arguments displayed.

api8.JPG

Now you can POST this API by entering the value of each parameter when hitting the API on the left side and clicking "Send Request" at the bottom right.

Step 5: What you want to be described in the API description

Finally, I will explain what I want you to describe in the API description.

** What is important is a compassionate desire to create API documentation that is easy to understand and understand from the perspective of the user using the API. ** **

The content you want to describe differs greatly depending on whether the API is used only inside the system by the development team or if the API is exposed to the outside.

anyway,

--API operation summary (results produced) --Details of API operation (If there is a link to the UML diagram, describe the link) --HTTP response status code in normal form of API and returned contents --Arguments (name, description, required, type) --Abnormal HTTP response status code and returned contents

I want it.

For other contents that should be described in the API

● Book "Web API Design" https://www.amazon.co.jp/dp/4798167010/

● Google API Design Guide https://cloud.google.com/apis/design

● MS API Design Guide https://docs.microsoft.com/ja-jp/azure/architecture/best-practices/api-design

● API style book http://apistylebook.com/

I think it's a good idea to match up how much you write with your own team, referring to the above.

This is how to automatically generate API document with Django REST framework & POST from document screen.


Remarks

【Transmission of information】 In addition to the impressions of the books I read, I publish articles and sites on Twitter that I find interesting in IT / AI and business / management. If you want to collect information on these fields, please follow us ♪ (There is a lot of overseas information)

Yutaro Ogawa @ISID_AI_team https://twitter.com/ISID_AI_team

** [Other] ** The "AI Technology Department Development Team" that I lead is looking for members. If you are interested This page Thank you ♪

** [Sokumen-kun] ** If you want to apply suddenly, we will have a casual interview with "Sokumen-kun". Please use this as well ♪ https://sokumenkun.com/2020/08/17/yutaro-ogawa/

[Disclaimer] The content of this article itself is the opinion / transmission of the author, not the official opinion of the company to which the author belongs.


Other references in this article

Recommended Posts

How to automatically generate API document with Django REST framework & POST from document screen
How to reset password via API using Django rest framework
CRUD POST with Nuxt & Django REST Framework
Create a REST API to operate dynamodb with the Django REST Framework
How to deal with garbled characters in json of Django REST Framework
How to create a Rest Api in Django
When you want to filter with Django REST framework
How to post a ticket from the Shogun API
Sometimes you want to access View information from Serializer with DRF (Django REST Framework)
Django REST framework with Vue.js
Login with django rest framework
How to write custom validations in the Django REST Framework
Automatically generate model relationships with Django
How to get started with Django
[Django] Use MessagePack with Django REST framework
How to authenticate with Django Part 2
How to authenticate with Django Part 3
How to do arithmetic with Django template
Create RESTful APIs with Django Rest Framework
CRUD GET with Nuxt & Django REST Framework ②
Post from another account with Twitter API
CRUD GET with Nuxt & Django REST Framework ①
How to build an application from the cloud using the Django web framework
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
How to get people to try out django rest framework features in one file
Solution when Not Found appears when hitting the Django REST Framework API from the outside
CRUD PUT, DELETE with Nuxt & Django REST Framework
Generate and post dummy image data with Django
How to develop a cart app with Django
How to generate a Python object from JSON
How to call Cloud API from GCP Cloud Functions
Try to automatically generate Python documents with Sphinx
How to implement "named_scope" of RubyOnRails with Django
Django REST framework A little useful to know.
Implementing authentication in Django REST Framework with djoser
[Learning memo] How to make an application with Django ~ From virtual environment to pushing to github ~
Create a Todo app with Django REST Framework + Angular
More new user authentication methods with Django REST Framework
How to scrape image data from flickr with python
Create a Todo app with the Django REST framework
Create APIs around user authentication with Django REST Framework
How to use Azure Table storage from Django (PTVS)
I tried to automatically generate a password with Python3
How to analyze with Google Colaboratory using Kaggle API
Transit to the update screen with the Django a tag
How to operate Discord API with Python (bot registration)
Implement hierarchical URLs with drf-nested-routers in Django REST framework
I tried to automatically post to ChatWork at the time of deployment with fabric and ChatWork Api
How to register the same data multiple times with one input on the Django management screen
Django REST framework basics
Django Rest Framework Tips
[Evangelion] Try to automatically generate Asuka-like lines with Deep Learning
How to handle static files when deploying to production with Django
How to output a document in pdf format with Sphinx
How to check ORM behavior in one file with django
[Django] How to give input values in advance with ModelForm
How to generate a public key from an SSH private key
How to log in automatically like 1Password from the CLI
How to resolve CSRF Protection when using AngularJS with Django
How to generate a query using the IN operator in Django
How to do the initial setup from Django project creation