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.
This time, I am using ** version: 3.10.3 **. The latest version (September 2020) is ** version: 3.11.1 **.
Install the packages required for automatic API documentation.
pip install coreapi
pip install Pygments
pip install Markdown
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.
** * 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/
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
** * 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).
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)
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.
In addition, when describing the API description, what kind of content should be described will be explained at the end of this article.
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.
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.
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".
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.
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.
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.
【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.
Recommended Posts