Documenting your API using Open API (Swagger) and Redoc in Django Rest Framework.

Mo. Torkashvand
3 min readJun 26, 2020

In the software industry, the API is a great way to share your service and data with the rest of the word and have seamless connectivity with other separate pieces of software. To access APIs effectively they need clear documentation. Also, it is a key point for API maintenance to establish a common understanding of current and future features among all stakeholders.

There are some ways to document your APIs such as RAML and Open API (former Swagger) which allow you to describe the structure of your APIs in order to be read by machines automatically.

In this tutorial, I want to show you how we can create API documentation using Open API, Redoc, and the Django Rest Framework aka DRF. To do that I want to usedrf-yasg a Django third-party package. Talking is enough! let's do that step by step:

1: Install drf-yasg:

Install the drf-yasgpackage with a package manager of your choice eg: pip and add it to your requirement file.

2: Add drf-yasg to your INSTALLED_APPS:

3: Create base XcodeAutoSchema:

If the default spec generation does not quite match what you were hoping to achieve, drf-yasg provides some custom behavior hooks by default which I want to override some of its behaviors to add redoc support.

4: Create a concrete XcodeAutoSchema class:

For each API view that you want to document create an XcodeAutoSchema class inherited from the base one which we have created before.

5: Create the required code example templates:

I use the Django template system and its render_to_string() function to create python and curl sample codes and keep my code clean and dynamic as well. you can pass your context to code sample templates such as the requested URL.

6: Add the XcodeAutoSchema to your API View:

You can use the @swagger_auto_schema a decorator on view functions to override some properties of the generated Operation. The parameters passed to this decorator take precedence over the auto-generated schema.

7: Add required routes into url.py file:

Run your code and you will see the magic in the browser!:

That’s is, Done!

Please share your thoughts in the comments below. If you like the article Clap! your hands, Also for reading my other articles, please Follow Me as well.

--

--

Mo. Torkashvand

Experienced Python backend developer, who loves sharing his experience with the community. His Linkedin profile: https://www.linkedin.com/in/mo-torkashvand/