DEV Community

Cover image for Building a Django-Powered API with Swagger
nisrine
nisrine

Posted on • Edited on

Building a Django-Powered API with Swagger

Workarise is a Software as a Service (SaaS) startup specializing in collaboration and project management. To enhance the platform's capabilities and make it more accessible, I recently built an API for Workarise using Python, Django, and Swagger. In this article, I'll provide a brief overview of the project and explain how I created the API.

Why Django and Python?

Django is a powerful web framework for Python that allows developers to build web applications quickly and efficiently. We chose Django and Python for their ease of use, scalability, and the vast ecosystem of libraries available. Additionally, Python's readability and simplicity make it an excellent choice for API development.

Why Swagger API?

Swagger, now known as OpenAPI, is a widely adopted specification for describing and documenting RESTful APIs. It offers a range of tools that simplify the API design, development, and documentation processes. We chose Swagger because it enhances developer experience, makes the API easier to maintain, and enables seamless integration with various client libraries.

Swagger UI:

One of the key features of Swagger is its user-friendly UI, which makes it easier for developers and non-developers to interact with the API. Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate well-structured documentation and a sandbox to try out API calls from a web browser. This interactive documentation allows users to understand and explore the API's capabilities without having to dive into the codebase. To integrate Swagger UI with your Django project, you can use packages like 'drf-yasg' or 'django-rest-swagger'.

Building the API:

To create the API, I started by setting up a separate app called swaggerapi and add it to the installed apps list in the project's settings. This app contains the following essential components:

  • Serializers: The serializers.py file contains serializers that define how the models should be serialized to JSON format. Serializers are crucial for defining the input and output data format of the API endpoints. For this project, I used Django Rest Framework's serializers.ModelSerializer to create serializers for the models. ModelSerializer is a shortcut for creating serializers that deal with model instances and querysets. It automatically generates a set of fields and default validation based on the model's fields, like this:
class YourModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = YourModel
        fields = '__all__'
Enter fullscreen mode Exit fullscreen mode
  • API Views: this file would contain the API views, which define the behavior and logic of the API endpoints. Django Rest Framework (DRF) provides generic views that handle common patterns like creating, retrieving, updating, and deleting objects. Examples of these generic views are generics.ListCreateAPIView and generics.RetrieveUpdateDestroyAPIView. These views help you to create CRUD operations for the models with minimal code. Implementation example:
class YourModelListCreateAPIView(generics.ListCreateAPIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [permissions.IsAuthenticated]
    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer

Enter fullscreen mode Exit fullscreen mode

ListCreateAPIView, for example, is a combination of a list view that displays a queryset and a create view that allows you to create a new instance. It uses the serializer_class to convert the model instances to JSON format.

  • Authentication and Permission classes: DRF provides a set of built-in authentication classes, like TokenAuthentication or JWTAuthentication, that handle user authentication. To use JWT authentication, you need to install the 'djangorestframework_simplejwt' package and import the JWTAuthentication class:
from rest_framework_simplejwt.authentication import JWTAuthentication
Enter fullscreen mode Exit fullscreen mode

Permission classes define who has access to certain API views. DRF includes several built-in permission classes, such as IsAuthenticated, IsAdminUser, and IsAuthenticatedOrReadOnly. You can also create custom permission classes if needed.

  • Queryset: In DRF, a queryset is a collection of objects from your database that match specific conditions. It allows you to perform operations like filtering, ordering, or slicing the data. In API views, you define the queryset using the 'queryset' attribute. The queryset is then used by the view to display the data or perform actions like creating, updating, or deleting objects.

  • URL Schemas and Swagger Schemas: When building an API, it's essential to define the URL patterns that map to specific API views. In the 'urls.py' file of your 'swaggerapi' app, you can define these URL patterns using Django's built-in functions like 'path()' or 're_path()'. For example:

from django.urls import path
from . import views

urlpatterns = [
    path('yourmodel/', views.YourModelListCreateAPIView.as_view(), name='yourmodel-listcreate'),
    path('yourmodel/<int:pk>/', views.YourModelRetrieveUpdateDestroyAPIView.as_view(), name='yourmodel-retrieveupdatedestroy'),
]
Enter fullscreen mode Exit fullscreen mode

In addition to defining the URL patterns, it's also important to create Swagger schemas that describe the structure of the API. Swagger schemas are written in YAML or JSON format and include information such as the API's endpoints, HTTP methods, request parameters, and response objects. By documenting your API with Swagger schemas, you can generate interactive documentation that helps users understand and explore your API's capabilities.

To include the Swagger schemas in your Django project, you can use packages like 'drf-yasg', which provides a set of tools to generate OpenAPI schemas from your Django Rest Framework views. After installing the package, you can configure your 'urls.py' file to include the schema view like this:

from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="Your API",
        default_version='v1',
        description="API documentation for your project",
    ),
    public=True,
)

urlpatterns += [
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]
Enter fullscreen mode Exit fullscreen mode

in the main 'urls.py' file of your Django project, add a path to include the 'swaggerapi.urls'. This will ensure that your API views are accessible through the specified URL patterns.

By following these steps, you can create a functional, well-documented API for your project using Django, Python, and Swagger. This API will be efficient and maintainable, and it will enable you to enhance your platform's capabilities, making it more accessible to users.

Top comments (0)