Setting up Django Rest Framework (DRF) in Django


In this article, we will guide you through setting up Django Rest Framework (DRF) in a Django project. DRF is a powerful toolkit that simplifies the process of building RESTful APIs in Django. It provides features such as authentication, serialization, and viewsets, making it easier to expose your models as APIs.

1. Installing Django Rest Framework (DRF)

The first step is to install Django Rest Framework. You can install DRF via pip, the Python package manager.

            
    pip install djangorestframework
            
        

Once DRF is installed, you need to add it to your Django project's settings.

Example: Updating the Settings

            
    # settings.py
    INSTALLED_APPS = [
        # Other installed apps
        'rest_framework',  # Add this line to include DRF in your project
    ]
            
        

After adding DRF to your INSTALLED_APPS, you are ready to start using it to create API views and serializers.

2. Creating a Simple Model

Before we create an API, let's define a simple model. For this example, we'll create a model called Book, which will represent books in our system.

            
    # models.py
    from django.db import models

    class Book(models.Model):
        title = models.CharField(max_length=100)
        author = models.CharField(max_length=100)
        publish_date = models.DateField()

        def __str__(self):
            return self.title
            
        

In this example, the Book model has three fields: title, author, and publish_date.

3. Creating a Serializer for the Model

In DRF, you need to create serializers to convert your models into JSON format (and vice versa). A serializer defines how to translate the data between Django models and JSON responses.

Example: Creating a Book Serializer

            
    # serializers.py
    from rest_framework import serializers
    from .models import Book

    class BookSerializer(serializers.ModelSerializer):
        class Meta:
            model = Book
            fields = ['id', 'title', 'author', 'publish_date']
            
        

In this example, we define a BookSerializer class that inherits from serializers.ModelSerializer. The fields attribute specifies which fields of the model should be included in the API output.

4. Creating API Views

In DRF, views are used to handle the logic for serving API responses. You can use either function-based views or class-based views to define how your API should behave.

Example: Creating a Simple API View for Book Model

            
    # views.py
    from rest_framework import generics
    from .models import Book
    from .serializers import BookSerializer

    class BookListCreate(generics.ListCreateAPIView):
        queryset = Book.objects.all()
        serializer_class = BookSerializer

    class BookDetail(generics.RetrieveUpdateDestroyAPIView):
        queryset = Book.objects.all()
        serializer_class = BookSerializer
            
        

In this example, we use DRF’s generic views to create API views for listing and creating books (using ListCreateAPIView) and retrieving, updating, or deleting a specific book (using RetrieveUpdateDestroyAPIView). The queryset attribute defines which data will be used by the view, and serializer_class tells the view which serializer to use for the response.

5. Adding URL Routing for the API

Next, we need to create URL routes to map the API views. DRF provides a convenient DefaultRouter to automatically create URLs for your API views.

Example: Setting Up URLs for Book API

            
    # urls.py
    from django.urls import path, include
    from rest_framework.routers import DefaultRouter
    from .views import BookListCreate, BookDetail

    router = DefaultRouter()
    router.register(r'books', BookListCreate, basename='book')

    urlpatterns = [
        path('api/', include(router.urls)),  # Include the DRF-generated URLs
        path('api/books//', BookDetail.as_view(), name='book-detail'),
    ]
            
        

In this example, we use DefaultRouter to automatically create routes for listing and creating books. We also add a URL for the BookDetail view, which will handle retrieving, updating, and deleting a single book by its primary key (pk).

6. Testing the API

Once the views and URLs are set up, you can test your API by running the Django development server and making requests to the API endpoints.

            
    # Run the server
    python manage.py runserver
            
        

After starting the server, you can visit the following endpoints:

  • GET /api/books/ to list all books.
  • POST /api/books/ to create a new book.
  • GET /api/books/{id}/ to retrieve a single book by its ID.
  • PUT/PATCH /api/books/{id}/ to update a book's details.
  • DELETE /api/books/{id}/ to delete a book.

7. Conclusion

In this article, we have walked through the process of setting up Django Rest Framework (DRF) in a Django project. We covered installing DRF, creating a model, serializing the model data, setting up API views, and creating URL routes to expose your API. With this basic setup, you can now start building more complex APIs using DRF and integrate it into your Django application.





Advertisement