Published May 4, 2024 ⦁ 9 min read
Swagger Python Django Integration Guide

Swagger Python Django Integration Guide

Swagger is an open-source tool that helps developers design, build, document, and test RESTful APIs. Django is a high-level Python web framework that provides a powerful toolkit for building Web APIs. Integrating Swagger with Django allows you to generate interactive API documentation, streamlining development and collaboration.

Key Benefits

  • Improved API discoverability with comprehensive, interactive documentation
  • Easier collaboration among team members and stakeholders
  • Faster development cycles with streamlined testing and documentation

Quick Setup

  1. Install drf-yasg: pip install drf-yasg
  2. Add to INSTALLED_APPS: INSTALLED_APPS = [..., 'drf_yasg']
  3. Configure Swagger settings: SWAGGER_SETTINGS = {...}
  4. Set up Swagger URLs: Define URL patterns for Swagger UI and ReDoc
  5. Add Swagger documentation: Use decorators and comments in Django views

Customization

  • Modify Swagger UI settings in SWAGGER_SETTINGS
  • Set authentication and permission classes for accessing documentation
  • Customize UI with templates and CSS/JS overrides

By following this guide, you can seamlessly integrate Swagger with your Django project, unlocking enhanced API documentation and testing capabilities for your development workflow.

Getting Ready

Before integrating Swagger with Django, you need to set up your environment and install the required software. This section will guide you through the necessary steps.

Required Software and Knowledge

To integrate Swagger with Django, you'll need:

Software Description
Python 3.x The latest version is recommended
Django The latest version is recommended
Django REST Framework The latest version is recommended
drf-yasg The latest version is recommended

Additionally, you should have a basic understanding of Django development, including:

  • Creating a new Django project, app, and model

Setting Up the Environment

Follow these steps to set up your environment:

1. Create a Python virtual environment:

python -m venv myenv

2. Activate the virtual environment:

source myenv/bin/activate

3. Install the required packages:

pip install django djangorestframework drf-yasg

4. Create a new Django project:

django-admin startproject myproject

5. Create a new Django app:

python manage.py startapp myapp

Now that you have the necessary software installed and the environment set up, you're ready to start integrating Swagger with Django.

Step 1: Install Swagger with Django

Swagger

Install the drf-yasg Package

drf-yasg

To integrate Swagger with Django, you need to install the drf-yasg package. This package generates Swagger/OpenAPI schemas for Django REST Framework APIs.

Open your terminal and run the following command to install drf-yasg using pip:

pip install drf-yasg

This command will download and install the drf-yasg package and its dependencies.

Update INSTALLED_APPS

After installing drf-yasg, you need to add it to the INSTALLED_APPS list in your Django project's settings.py file.

Open your settings.py file and add drf_yasg to the INSTALLED_APPS list:

INSTALLED_APPS Description
... ...
rest_framework Django REST Framework
drf_yasg Swagger/OpenAPI schema generator
... ...

This will enable drf-yasg to generate Swagger/OpenAPI schemas for your Django REST Framework API.

That's it! You have successfully installed drf-yasg and updated your INSTALLED_APPS list. In the next step, we will configure Swagger settings for your Django project.

Step 2: Configure Swagger Settings

In this step, we'll explore the configuration options available for Swagger within Django's settings.py file. This is crucial in customizing Swagger to suit your project's needs.

Public Accessibility

By default, Swagger is accessible to everyone. If you want to restrict access to Swagger, you can set USE_SESSION_AUTH to True in your SWAGGER_SETTINGS dictionary. This will enable Django's session-based authentication for Swagger.

SWAGGER_SETTINGS = {
    'USE_SESSION_AUTH': True,
    # Other settings...
}

Other Settings

You can also configure other Swagger settings, such as the title, description, and version of your API. These settings can be defined in the SWAGGER_SETTINGS dictionary.

Setting Description
TITLE The title of your API
DESCRIPTION A brief description of your API
VERSION The version of your API

Additionally, you can customize the Swagger UI by overriding the swagger-ui.html template. This allows you to add custom CSS, JavaScript, or HTML to the Swagger UI.

That's it for this step! In the next section, we will set up Swagger URLs in our Django project.

sbb-itb-b2281d3

Step 3: Set Up Swagger URLs

In this step, we'll create URL patterns to serve Swagger's dynamic documentation, including JSON/YAML endpoints and the UI interface.

Define URL Patterns

To set up Swagger URLs, you need to define URL patterns in your Django project's urls.py file. This file maps URLs to views, which generate the Swagger documentation.

Here's an example of how you can define Swagger URLs:

from django.urls import path, include
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="My API",
        default_version='v1',
        description="My API description",
        terms_of_service="https://www.example.com/terms/",
        contact=openapi.Contact(email="contact@example.com"),
        license=openapi.License(name="Awesome License"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]

Swagger URL Patterns Explained

In this example, we define two URL patterns: swagger/ and redoc/. The swagger/ URL pattern serves the Swagger UI, while the redoc/ URL pattern serves the ReDoc UI.

URL Pattern Description
swagger/ Serves the Swagger UI
redoc/ Serves the ReDoc UI

With these URL patterns defined, you can now access your Swagger documentation by navigating to http://localhost:8000/swagger/ or http://localhost:8000/redoc/ in your web browser.

Step 4: Add Swagger Documentation

Now that we have set up Swagger URLs, it's time to add Swagger documentation to our Django project. Swagger uses decorators and comments in Django views to provide metadata, which it uses to create accurate and useful documentation.

Using Decorators and Comments

To add Swagger documentation, you need to use decorators and comments in your Django views. Decorators are used to provide metadata about the view, such as the HTTP methods it supports, the request and response formats, and any authentication or permission requirements.

Here's an example of how you can use decorators to add Swagger documentation to a Django view:

from rest_framework.response import Response
from rest_framework import status
from drf_yasg.utils import swagger_auto_schema

class MyView(APIView):
    @swagger_auto_schema(
        operation_description="Get a list of all items",
        responses={200: "List of items"}
    )
    def get(self, request):
        # View logic here
        pass

    @swagger_auto_schema(
        operation_description="Create a new item",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'name': openapi.Schema(type=openapi.TYPE_STRING),
                'description': openapi.Schema(type=openapi.TYPE_STRING)
            }
        ),
        responses={201: "Item created successfully"}
    )
    def post(self, request):
        # View logic here
        pass

In this example, we use the swagger_auto_schema decorator to provide metadata about the get and post methods of the MyView view. The decorator takes an operation_description parameter, which provides a brief description of the operation, as well as a responses parameter, which specifies the possible responses and their corresponding status codes.

Adding Comments to Views

In addition to using decorators, you can also add comments to your views to provide additional metadata. Comments can be used to provide more detailed information about the view, such as the purpose of the view, the input and output formats, and any error handling or edge cases.

Here's an example of how you can add comments to a Django view:

class MyView(APIView):
    """
    This view returns a list of all items.

    **HTTP Method:** GET
    **Endpoint:** /items/
    """
    def get(self, request):
        # View logic here
        pass

    """
    This view creates a new item.

    **HTTP Method:** POST
    **Endpoint:** /items/
    **Request Body:**
    {
        "name": "string",
        "description": "string"
    }
    """
    def post(self, request):
        # View logic here
        pass

In this example, we add comments to the get and post methods of the MyView view to provide additional metadata. The comments are written in a specific format, with the first line providing a brief description of the view, and subsequent lines providing more detailed information about the input and output formats.

By using decorators and comments, you can provide Swagger with the metadata it needs to create accurate and useful documentation for your Django project.

Step 5: Run the Project

Now that we have set up Swagger URLs and added Swagger documentation to our Django project, it's time to run the project and verify that Swagger documentation is accessible and correctly documenting the API.

Running the Project

To run the project, navigate to the terminal and execute the following command:

python manage.py runserver

This command will start the Django development server.

Accessing Swagger Documentation

Once the server is running, you can access the Swagger UI documentation by visiting http://127.0.0.1:8000/swagger/ in your web browser.

Verifying Swagger Documentation

In the Swagger UI, you will see a list of endpoints, parameters, and response schemas for your API. You can explore and interact with your API directly from the Swagger UI, simplifying the development and testing process.

Make sure to check that the Swagger documentation is correctly generated and reflects the changes you made to your API. If you encounter any issues, review the previous steps to ensure that everything is set up correctly.

With the Swagger UI up and running, you can now use it to test and document your API, making it easier to maintain and evolve your API over time.

Customizing Swagger

Customizing Swagger allows you to personalize the look and feel, as well as the functionality, of the Swagger documentation generated for your Django API.

Modifying UI Settings

You can customize the Swagger UI settings using the SWAGGER_SETTINGS dictionary in your Django project's settings file. This dictionary allows you to modify various UI behaviors.

Setting Description
USE_SESSION_AUTH Toggles the use of Django Auth as an authentication mechanism

Authentication and Permissions

Swagger provides a range of authentication and permission classes that can be used to control access to the Swagger documentation. You can set authentication and permission classes for accessing the Swagger documentation using the LOGIN_URL and LOGOUT_URL settings.

Setting Description
LOGIN_URL Specifies the login URL for Swagger documentation
LOGOUT_URL Specifies the logout URL for Swagger documentation

Additionally, you can use the permission_classes parameter to specify the permission classes required to access the Swagger documentation.

Permission Class Description
permissions.AllowAny Allows anyone to access the Swagger documentation

By customizing the Swagger UI settings and authentication and permission classes, you can tailor the Swagger documentation to meet the specific needs of your Django API.

Conclusion

You've made it! You've successfully integrated Swagger with your Django project. This integration provides enhanced API documentation and testing capabilities.

What You've Achieved

By following this guide, you've:

  • Set up Swagger with Django
  • Configured Swagger settings
  • Added Swagger documentation to your Django project
  • Run the project and verified Swagger documentation

Next Steps

Now that you've integrated Swagger with Django, you can:

  • Explore further customization and optimization opportunities
  • Tailor the Swagger UI settings and authentication and permission classes to meet the specific needs of your Django API

The Benefits of Swagger and Django

Using Swagger with Django offers several benefits, including:

Benefit Description
Improved API Discoverability Swagger provides a comprehensive and interactive API documentation
Easier Collaboration Swagger enables better communication among team members and stakeholders
Faster Development Cycles Swagger streamlines the development process

By leveraging the power of Swagger and Django, you can take your API development to the next level.

Happy coding! 🚀

FAQs

How to Integrate Swagger in Django?

To integrate Swagger in Django, follow these steps:

  1. Install drf-yasg package:
pip install drf-yasg
  1. Add drf_yasg to INSTALLED_APPS:
INSTALLED_APPS = [
   ...
    'drf_yasg',
]
  1. Configure Swagger settings:
SWAGGER_SETTINGS = {
    'DEFAULT_MODEL_RENDERING': 'example',
    'DOC_EXPANSION': 'list',
}
  1. Set up Swagger URLs:
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="API Documentation",
        default_version='v1',
    ),
)

urlpatterns = [
   ...
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]

How to Set Up Swagger in Django REST Framework?

Django REST Framework

To set up Swagger in Django REST Framework, follow the same steps as above. Here's a summary:

Step Description
1 Install drf-yasg package
2 Add drf_yasg to INSTALLED_APPS
3 Configure Swagger settings
4 Set up Swagger URLs
5 Decorate Django REST Framework views with Swagger schema generation annotations
6 Run the Django development server and access the Swagger UI

By following these steps, you can easily integrate Swagger with your Django REST Framework API, providing interactive documentation and testing capabilities.