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!
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.
First, let's set up our project structure:
myproject/
myproject/
api/
views.py
urls.py
myapp/
models.py
urls.py
views.py
manage.pyIn Django, APIs are usually placed in a separate app named api.
Now, let's write a simple Class-Based API View for a Book model:
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.Book objects and serialize them using a custom serialize method.JsonResponse is used to return the serialized data as JSON.Let's create a new Book and retrieve it using a custom create and retrieve methods:
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).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! π