Class-Based API Views in Django

beginner
10 min

Class-Based API Views in Django

Welcome back to CodeYourCraft! Today, we're diving into one of the most powerful features of Django - Class-Based API Views. Let's get started!

πŸ“ What are Class-Based API Views?

Class-Based API Views are a flexible and powerful way to create APIs in Django. They provide a more granular control compared to the Function-based views.

🎯 Setting Up Class-Based API Views

First, let's set up our project structure:

bash
myproject/ myproject/ api/ views.py urls.py myapp/ models.py urls.py views.py manage.py

πŸ’‘ Pro Tip:

In Django, APIs are usually placed in a separate app named api.

πŸ“ Writing a Class-Based API View

Now, let's write a simple Class-Based API View for a Book model:

python
from django.http import JsonResponse from rest_framework.viewsets import ViewSet from myapp.models import Book class BookViewSet(ViewSet): def list(self, request): books = Book.objects.all() return JsonResponse([book.serialize() for book in books], safe=False)

In this code:

  • ViewSet is a base class provided by Django Rest Framework (DRF) for Class-Based API views.
  • list is a method that handles GET requests.
  • We fetch all the Book objects and serialize them using a custom serialize method.
  • JsonResponse is used to return the serialized data as JSON.

🎯 Practical Example: Create and Retrieve a Book

Let's create a new Book and retrieve it using a custom create and retrieve methods:

python
class BookViewSet(ViewSet): def list(self, request): books = Book.objects.all() return JsonResponse([book.serialize() for book in books], safe=False) def create(self, request): book = Book.objects.create( title=request.data['title'], author=request.data['author'] ) return JsonResponse(book.serialize(), status=201) def retrieve(self, request, pk): book = Book.objects.get(pk=pk) return JsonResponse(book.serialize())

In this code:

  • create handles POST requests and creates a new Book object.
  • retrieve handles GET requests for a specific book using the primary key (pk).

πŸ“ Quiz Time

Quick Quiz
Question 1 of 1

What is the base class for Class-Based API views in Django Rest Framework?

Stay tuned for more on Class-Based API views, including detailing the update and delete methods, and exploring DRF's built-in serializers! πŸŽ‰