GET Method Request in Django Rest Framework (DRF) with Example

When building a web application, it’s common to need an API (Application Programming Interface) to communicate and exchange data with the frontend or external services. Django Rest Framework (DRF) is a powerful tool that allows developers to quickly create APIs with Django, a popular web framework for Python. In this blog, we will explore the DRF GET method, which is used for retrieving data from the server, and provide a practical example to illustrate its usage.

Read our New Blog on How to Combine all API Methods like Get, Post, Put, Delete in One View

The GET Method in Django Rest Framework

In the context of RESTful APIs, the GET method is used to request data from the server. It is considered a safe and idempotent operation, meaning that multiple identical requests will produce the same result, and it should not have any side effects on the server’s data. The GET method is commonly used to fetch resources or data without modifying anything on the server.

In Django Rest Framework, handling GET requests is straightforward. You define a view that retrieves the data you want to serve and serialize it into a format that can be easily understood by the requesting client, typically JSON. DRF provides built-in functionality to handle serialization and deserialization of data.

Prerequisites:

Before we begin, ensure you have the following prerequisites in place:

  1. Django installed on your system.
  2. Basic familiarity with Django project structure and database concepts.
  3. Virtual Environment, this is optional but recommended. You check our blog here.

Note: For this tutorial, we are using our basic skeleton project for Django. You can also download the project from here.

Sample Django Model and Serializers for Examples

Step 1: Create the Django Model

First, define the Django model that represents a book. In your app’s models.py, add the following code:

from django.db import models

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

Don’t forget to run python manage.py makemigrations and python manage.py migrate to create the corresponding database table for the model.

Step 2: Create the Serializer

Next, create a serializer to convert the book model instances into JSON data and vice versa. In your app’s serializers.py, add the following code:

from rest_framework import serializers
from .models import Book

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

1. Django Rest Framework API with GET Method Request

Let’s create a simple API to manage a collection of books. For this example, we assume that you already have Django and Django Rest Framework installed in your project.

Step 1: Create the View

Now, create a view to handle GET requests for the book data. In your app’s views.py, add the following code:

from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

class BookListView(generics.ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

Step 2: Define the URL Pattern

Finally, define a URL pattern to map the view with a URL endpoint. In your project’s urls.py, add the following code:

from django.urls import path
from .views import BookListView

urlpatterns = [
    path('api/books/', BookListView.as_view(), name='book-list'),
]

Step 3: Test the API

Now that we have set up our API, you can start the Django development server by running python manage.py runserver. With the server running, you can access the API using your browser or tools like curl or Postman.

To retrieve all the books, simply make a GET rquest to the URL http://localhost:8000/api/books/, and the server will respond with a JSON array containing the list of books, each represented as an object with attributes id, title, author, and publication_date.

2. Django Rest Framework Get Method with Parameters

In the previous section, we learned how to create a simple Django Rest Framework API using the GET method to retrieve all books from the server. Now, let’s enhance our API to allow filtering of books based on certain parameters. This will enable clients to request specific subsets of data that match their criteria. We’ll add filtering based on the book’s publication year as an example.

Step 1: Modify the View

In our previous example, we used a ListAPIView to retrieve all books. To add parameter-based filtering, we need to use a ListCreateAPIView instead. Modify the views.py as follows:

from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

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

Step 2: Add Filtering Logic

Now, let’s update the BookListView to handle filtering based on the publication year. We’ll override the get_queryset() method to customize the queryset based on the URL parameters.

from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

class BookListView(generics.ListCreateAPIView):
    serializer_class = BookSerializer

    def get_queryset(self):
        queryset = Book.objects.all()
        publication_year = self.request.query_params.get('publication_year', None)

        if publication_year is not None:
            queryset = queryset.filter(publication_date__year=publication_year)

        return queryset

Step 3: Define the URL Pattern

The URL pattern remains the same as in the previous example. In your project’s urls.py, it should look like this:

from django.urls import path
from .views import BookListView

urlpatterns = [
    path('api/books/', BookListView.as_view(), name='book-list'),
]

Step 4: Test the API with Parameters

With the modified API, you can now filter books based on their publication year. To do this, make a GET request to the URL http://localhost:8000/api/books/ with the parameter publication_year set to the desired year. For example, to get books published in the year 2022, use the URL http://localhost:8000/api/books/?publication_year=2022.

The server will respond with a JSON array containing only the books that match the specified publication year.

3. DRF Get Request Single Resource (Get One)

In addition to retrieving all resources, there are situations where you might need to fetch a single resource based on its unique identifier. In RESTful APIs, this operation is commonly referred to as “Get One” or “Retrieve” operation. In this section, we’ll enhance our Django Rest Framework API to support fetching a single book using the GET method and its corresponding unique identifier, typically the primary key (id).

Step 1: Modify the View

To handle the “Get One” operation, we’ll modify our view to use a RetrieveAPIView instead of ListCreateAPIView. The RetrieveAPIView is designed specifically to handle retrieving a single resource based on its unique identifier. Update the views.py as follows:

from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

class BookDetailView(generics.RetrieveAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

Step 2: Define the URL Pattern

Next, define a URL pattern to map the new view with a URL endpoint that includes the unique identifier (in this case, the book’s id). In your project’s urls.py, add the following code:

from django.urls import path
from .views import BookListView, BookDetailView

urlpatterns = [
    path('api/books/', BookListView.as_view(), name='book-list'),
    path('api/books/<int:pk>/', BookDetailView.as_view(), name='book-detail'),
]

Step 3: Test the API to Retrieve a Single Book

With the updated view and URL pattern, you can now retrieve a single book by making a GET request to the URL http://localhost:8000/api/books/<book_id>/, where <book_id> is the unique identifier (primary key) of the book you want to retrieve.

For example, if you want to get the book with id=1, you would make a GET request to http://localhost:8000/api/books/1/.

The server will respond with a JSON object representing the book with the specified id.

Conclusion

In this blog post, we explored the GET method in Django Rest Framework, which is used to retrieve data from the server. We have also extended our Django Rest Framework API with the GET method to support filtering based on parameterss. Also expanded our Django Rest Framework API to support retrieving a single book using the GET method and its unique identifier.

Find this tutorial on Github.

Blogs You Might Like to Read!