Creating API Views and Serializers

Tutorial 2 of 5

1. Introduction

1.1 Brief explanation of the tutorial's goal

In this tutorial, our goal is to learn how to create API views and serializers using Django REST framework.

1.2 What the user will learn

You will learn how to serialize your data, which means converting complex data types, such as querysets and model instances, into Python data types. You'll also build the logic for your API's endpoints, creating views that handle incoming HTTP requests to your web application.

1.3 Prerequisites (if any)

  • Basic knowledge of Python
  • Familiarity with Django
  • Basic understanding of HTTP methods (GET, POST, PUT, DELETE)
  • Django REST Framework installed in your working environment

2. Step-by-Step Guide

2.1 Detailed explanation of concepts

  • Serializers: Django Rest Framework provides serializers for data serialization. This process translates Django models into other formats like JSON, XML or YAML for transmission over the network.
  • Views: In Django, a view is a Python function that receives a web request and returns a web response. In the context of the REST framework, views will be used to serve HTTP endpoints.

2.2 Clear examples with comments

Creating a serializer:

from rest_framework import serializers
from .models import Article

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'title', 'content')

Here, ArticleSerializer is a subclass of ModelSerializer, an in-built class in Django REST framework that provides a shortcut for creating serializers. The Meta class inside it is specifying which model it should serialize and what fields it should include.

Creating a view:

from rest_framework import viewsets
from .serializers import ArticleSerializer
from .models import Article

class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

Here, ArticleViewSet is a subclass of the ModelViewSet class. It uses the ArticleSerializer we declared earlier and applies it to all Article objects.

2.3 Best practices and tips

  • Always name your serializers as <ModelName>Serializer to maintain consistency.
  • Use ModelViewSet when you want to provide the full set of standard list, create, retrieve, update, destroy style operations.
  • Always use the serializers.ModelSerializer as it gives you a lot of functionality for free.

3. Code Examples

3.1 Multiple practical examples

# models.py
from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    def __str__(self):
        return self.title


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

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'title', 'content')


# views.py
from rest_framework import viewsets
from .serializers import ArticleSerializer
from .models import Article

class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

4. Summary

We have learned how to create serializers and views in Django REST Framework. You now know how to serialize your data and build the logic for your API's endpoints.

5. Practice Exercises

  1. Create a new model Author with fields name and email. Then create a serializer for it.
  2. Create a view for the Author model.
  3. Add a foreign key relationship from Article to Author. Update your serializers and views to reflect this change.

6. Solutions

# models.py
class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

# serializers.py
class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ('id', 'name', 'email')
# views.py
class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer
# models.py
class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

# serializers.py
class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'title', 'content', 'author')

# views.py
class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

You can now proceed to learn more about Django REST Framework's features like authentication and permissions.