Creating a Basic Retrieve API with Django REST Framework

Last updated 1 month, 2 weeks ago | 128 views 75     5

Tags:- Python Django DRF

A Retrieve API is used to fetch a single record from the database using its unique identifier (usually id). It is one of the key components of a RESTful API.

In this article, we’ll build a GET /books/<id>/ endpoint that returns a single book from the database.


What is a Retrieve API?

A Retrieve API allows the client to access the details of a specific object.

For example:

GET /books/1/

Response:

{
  "id": 1,
  "title": "Atomic Habits",
  "author": "James Clear"
}

Step-by-Step: Build a Retrieve API

Let’s walk through how to create a simple retrieve endpoint using Django REST Framework.


1. Set Up Your Django Project

Assuming you already have a project set up and an app called books, make sure the following packages are installed:

pip install django djangorestframework

Add the necessary apps to your settings:

# settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
    'books',
]

2. Define the Model

# books/models.py
from django.db import models

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

    def __str__(self):
        return self.title

Run the migrations:

python manage.py makemigrations
python manage.py migrate

3. Create the Serializer

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

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

4. Create the RetrieveAPIView

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

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

RetrieveAPIView automatically handles GET requests for a single object based on the primary key (pk).


5. Add the URL Pattern

# books/urls.py
from django.urls import path
from .views import BookRetrieveView

urlpatterns = [
    path('books/<int:pk>/', BookRetrieveView.as_view(), name='book-retrieve'),
]

Include it in the main urls.py:

# myapi/urls.py
from django.urls import path, include

urlpatterns = [
    path('api/', include('books.urls')),
]

✅ Testing the Retrieve API

Start the development server:

python manage.py runserver

Visit:

GET http://127.0.0.1:8000/api/books/1/

If a book with ID 1 exists, you’ll get:

{
  "id": 1,
  "title": "Atomic Habits",
  "author": "James Clear"
}

If the book does not exist:

{
  "detail": "Not found."
}

Summary

Component Description
RetrieveAPIView DRF generic view to handle GET //
pk in URL Used to fetch a single record by ID
BookSerializer Converts model instance to JSON
URL pattern Binds view to a dynamic path

⚠️ Common Issues

Problem Fix
404 Not Found Check if the ID exists in the database
Wrong path Make sure the path includes <int:pk>
Wrong method Ensure you're using a GET request, not POST or PUT

Tips

  • Use Django Admin to quickly create sample data.

  • You can use RetrieveAPIView as part of a complete RetrieveUpdateDestroyAPIView for full object-level actions.

  • Add lookup_field = 'slug' if you prefer using slugs instead of IDs.


What’s Next?

You now have a fully functioning Retrieve API. You can now explore:

  • ListAPIView to return multiple objects

  • CreateAPIView to allow creating new items

  • UpdateAPIView and DestroyAPIView

  • ModelViewSet to combine all actions in one view