Speakeasy Logo
Skip to Content
OpenAPI HubFrameworksDjango

How to generate an OpenAPI document with Django and Django REST framework

OpenAPI is a tool for defining and sharing REST APIs, and Django can be paired with Django REST framework to build such APIs.

This guide walks you through generating an OpenAPI document from a Django project and using it to create SDKs with Speakeasy, covering the following steps:

  1. Setting up a simple Django REST API with djangorestframework
  2. Integrating drf-spectacular
  3. Creating the OpenAPI document to describe the API
  4. Customizing the OpenAPI schema
  5. Using the Speakeasy CLI to create an SDK based on the schema
  6. Integrating SDK creation into CI/CD workflows

Requirements

This guide assumes you have a basic understanding of Django project structure and how REST APIs work.

You will also need the following installed on your machine:

  • Python version 3.8 or higher

  • Django

    You can install Django using the following command:

  • Django REST Framework

    You can install Django REST Framework using the following command:

Example Django REST API repository

The example repository contains all the code covered in this guide. You can clone it and follow along with the tutorial or use it as a reference to add to your own Django project.


Creating the OpenAPI document to describe an API

To better understand the process of generating an OpenAPI document with Django, let’s start by inspecting some simple CRUD endpoints for an online library, along with a Book class and a serializer for the data.

Models, serializers, and views

Let’s look at the key components of our Django REST API:

Book Model

First, let’s examine the books/models.py file, which contains a Book model with validation fields:

Book Serializer

Next, let’s look at the books/serializers.py file, which defines a BookSerializer for serializing and deserializing Book data:

Book Views

The books/views.py file contains a BookViewSet that handles CRUD operations for the Book model:

This code defines a simple Django REST API with CRUD operations for the Book model. The BookViewSet provides a way to interact with the Book model through the API. It also contains a custom action called author_books that retrieves all books by the same author.

URL Configuration

The books/urls.py file maps the BookViewSet to the /books endpoint:

And in the books_project/urls.py file, the router is included in the main Django URL configuration:

Integrate drf-spectacular

Django no longer supports the built-in OpenAPI document generation, so we’ll use the drf-spectacular package to generate the OpenAPI document.

Run the following to install drf-spectacular:

Setting up drf-spectacular

First, open the books_project/settings.py file to see how drf-spectacular is configured:

Adding 'drf_spectacular' to the INSTALLED_APPS list enables OpenAPI document generation for your Django project.

Next, check the REST_FRAMEWORK configuration object, which sets the schema class used to create the OpenAPI document:

The SPECTACULAR_SETTINGS dictionary contains additional settings for OpenAPI document generation that you can customize to fit your project:

In the books_project/urls.py file, the OpenAPI schema and Swagger UI endpoints are added alongside the api/ endpoint:

Apply migrations and run the server

To inspect and interact with the OpenAPI document, you need to apply database migrations and run the development server.

Apply database migrations:

Run the development server:

You can now access the API and documentation:

  • Visit http://127.0.0.1:8000/api/books/ to interact with the book API.
  • Visit http://127.0.0.1:8000/swagger/ for Swagger documentation.

OpenAPI document generation

Now that we understand our Django REST API, we can generate the OpenAPI document using drf-spectacular with the following command:

Exploring the Generated OpenAPI Document

Running the command generates an OpenAPI document in the openapi.yaml file. Let’s look at some key sections:

Document Header

The beginning of the document contains general information about the API:

Settings Influence on Generated Document

The values in SPECTACULAR_SETTINGS directly influence the OpenAPI document generation. For example, the title, description, and version in the settings:

These values appear in the OpenAPI document:

Server Information

The server URLs specified in the settings appear in the document as well:

Model Parameters

The fields we defined in our Django models are also reflected in the OpenAPI document. For example, the Book model fields:

These fields appear in the OpenAPI document’s schema definitions:

The OpenAPI document captures all the essential information about our API, including endpoints, parameters, request bodies, responses, and schemas. This document can then be used to generate client SDKs or API documentation.

OpenAPI document customization

The OpenAPI document generated by drf-spectacular may not be detailed enough for all use cases. Fortunately, it can be customized to better serve information about your API endpoints. You can add descriptions, tags, examples, and more to make the documentation more informative and user-friendly.

In the customized  branch of the example repository, you can find a customized OpenAPI document that demonstrates the available options for modifying your generated document.

The drf-spectacular package provides decorators to directly modify the schema for your views and viewsets.

  • @extend_schema_view: Allows customization of all methods in a viewset.
  • @extend_schema: Allows customization of individual methods or actions.

Customizing the API Schema

Let’s explore how to enhance the OpenAPI document by customizing the schema of the BookViewSet. Here’s an updated version of the books/views.py file with added annotations:

Using @extend_schema_view

The @extend_schema_view decorator allows you to customize all methods in a viewset at once. In our example, we’re customizing the list and retrieve operations with summaries, descriptions, and response details.

This will appear in the generated OpenAPI document as:

Customizing Individual Actions with @extend_schema

For specific actions like author_books, we use the @extend_schema decorator to add detailed documentation:

This will generate OpenAPI documentation for this endpoint:

Adding Custom Parameters

You can add custom query parameters to your endpoints using OpenApiParameter:

Adding Examples

Examples help API users understand the expected responses:

Adding Retry Logic

You can add retry configuration at the global level in settings.py:

Or apply it to specific endpoints using the extensions parameter in @extend_schema:

In summary, the drf-spectacular package provides a variety of ways to customize the OpenAPI document for your Django REST API. You can use decorators, tags, descriptions, parameters, fields, examples, and global settings to modify the document according to your requirements.

  • Decorators (@extend_schema and @extend_schema_view): Customize individual methods or entire views.
  • Tags and descriptions: Organize endpoints for better readability.
  • Parameters: Define custom parameters using OpenApiParameter.
  • OpenAPI components: Use OpenApiExample to provide reusable components or examples.
  • Global settings (SPECTACULAR_SETTINGS): Modify the global behavior of drf-spectacular.

For more information about customizing the OpenAPI schema with drf-spectacular, refer to the official drf-spectacular documentation.

Creating SDKs for a Django REST API

To create a Python SDK for the Django REST API, run the following command:

Follow the onscreen prompts to provide the configuration details for your new SDK, such as the name, schema location, and output path. When prompted, enter openapi.yaml for the OpenAPI document location, select a language, and generate.

Add SDK generation to your GitHub Actions

The Speakeasy sdk-generation-action repository provides workflows for integrating the Speakeasy CLI into your CI/CD pipeline, so that your SDKs are recreated whenever your OpenAPI document changes.

You can set up Speakeasy to automatically push a new branch to your SDK repositories for your engineers to review before merging the SDK changes.

For an overview of how to set up automation for your SDKs, see the Speakeasy SDK Generation Action and Workflows documentation.

SDK customization

Explore the effects of your newly generated OpenAPI document on the SDK created by Speakeasy.

After creating your SDK with Speakeasy, you will find a new directory containing the generated SDK code. Let’s explore this code a bit further.

These examples assume a Python SDK named books-python was generated from the example Django project above. Edit any paths to reflect your environment if you want to follow in your own project.

Exploring the Generated SDK

After generating your SDK with Speakeasy, let’s explore the key files and how they relate to your OpenAPI document.

The Book Class

Navigate to the books-python/src/books directory to find the generated SDK code. The book.py file contains the Book class that corresponds to your Django model:

API Client Code

The api.py file contains methods that call the web API from an application using the SDK:

Notice several important parameters:

  1. The server_url parameter, which comes from the SERVERS key in your SPECTACULAR_SETTINGS:
  1. The retries parameter, which is generated from your retry configuration:

Making API Requests

These parameters are used to build requests to your API endpoints:

Retry Logic Implementation

The SDK includes a retry implementation based on your OpenAPI extensions:

This retry logic directly reflects the configuration you provided in the x-speakeasy-retries extension in your OpenAPI document, ensuring consistent behavior between your API documentation and the generated SDK.

Summary

In this guide, we showed you how to generate an OpenAPI document for a Django API and use Speakeasy to create an SDK based on the OpenAPI document. The step-by-step instructions included adding relevant tools to the Django project, generating an OpenAPI document, enhancing it for improved creation, using Speakeasy OpenAPI extensions, and interpreting the basics of the generated SDK.

We also explored automating SDK generation through CI/CD workflows and improving API operations.

Last updated on