Django Rest Framework: A Beginner’s Guide

Azeem Akhtar
9 min readApr 15, 2023

Django is a high-level Python web framework enabling developers to build web applications easily. It provides a powerful and flexible toolkit for building APIs essential for modern web applications. One of the most popular ways to build APIs with Django is by using Django Rest Framework (DRF). In this article, we will explore DRF in-depth and discover why it is so popular among developers.

What is Django Rest Framework?

Django Rest Framework is a powerful and flexible toolkit that allows developers to build APIs quickly and easily. It is built on top of Django and provides tools that make it easy to serialize and deserialize complex data types, create CRUD endpoints, and handle authentication and permissions.

Why use Django Rest Framework?

DRF offers many benefits, including:

  • Easy integration with Django
  • Flexible serializers that can handle complex data types
  • Powerful views and view sets that make it easy to create CRUD endpoints
  • Built-in authentication and permission classes that make it easy to secure your API
  • Easy testing and debugging

Prerequisites for using Django Rest Framework

Before getting started with DRF, it is important to have a basic understanding of Django and Python. You should also be familiar with RESTful APIs and HTTP protocols.

Getting Started with Django Rest Framework

Installing Django Rest Framework

The first step in getting started with DRF is to install it. You can do this using pip, the Python package manager. Simply run the following command:

pip install djangorestframework

Setting up a Django Rest Framework project

Once you have installed DRF, you can create a new Django project and add DRF to it. To create a new project, run the following command:

django-admin startproject myproject

To add DRF to your project, you need to add it to your INSTALLED_APPS setting in your project’s settings.py file:

INSTALLED_APPS = [
# ...
'rest_framework',
]

Creating a Django Rest Framework app

Next, you must create a new app within your Django project containing your API views and serializers. To create a new app, run the following command:

python manage.py startapp api

Running the development server

To test your DRF app, you must run the Django development server. To do this, run the following command:

python manage.py runserver

Serializers

What are serializers?

Serializers in DRF allow you to convert complex data types, such as Django model instances, into JSON or XML format. They also allow you to validate incoming data and deserialize it into complex data types.

Serializing Django models

To serialize a Django model, you must create a serializer class that defines the fields you want to include in the serialized output. For example:

from rest_framework import serializers
from myapp.models import MyModel

class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ['field1', 'field2', 'field3']

Serializing other data types

DRF serializers can also be used to serialize other data types, such as lists and dictionaries. For example:

class MyListSerializer(serializers.ListSerializer):
child = serializers.CharField()

class MySerializer(serializers.Serializer):
my_list = MyListSerializer()

Customizing serializers

DRF serializers can be customized in several ways, such as by adding custom validation logic or custom fields. For example:

class MySerializer(serializers.Serializer):
my_field = serializers.CharField()

def validate_my_field(self, value):
if value == 'invalid':
raise serializers.ValidationError("Invalid value")
return value

Deserializing data

Deserialization converts the data from a format such as JSON or XML to a Django model instance. Django Rest Framework provides deserializes to handle this conversion automatically. In addition to the built-in deserializes, you can also create custom deserializes to handle more complex data.

Views and Viewsets

Views and Viewsets are used to define the behavior of an API endpoint. Views define how the endpoint should behave for each HTTP method, such as GET, POST, PUT, and DELETE. Viewsets are a higher-level abstraction that can handle multiple HTTP methods for the same endpoint.

What are views?

Views are responsible for processing HTTP requests and returning HTTP responses. In Django Rest Framework, views can be either function-based or class-based. Function-based views are simple Python functions that take an HTTP request as an argument and return an HTTP response. Class-based views are more flexible and can handle more complex logic.

What are viewsets?

Viewsets are a higher-level abstraction than views that allow you to define a set of related views for a single model or object. Viewsets handle multiple HTTP methods for the same endpoint, such as GET, POST, PUT, and DELETE. Viewsets can be further subclassed to provide additional functionality.

Class-based views vs. Function-based views

Class-based views are a more powerful and flexible way of defining views. They provide many functionalities out of the box, such as pagination, filtering, and authentication. Function-based views are simpler and easier to understand, but they can quickly become unmanageable as the complexity of the API grows.

Creating CRUD endpoints with views

Django Rest Framework provides several generic views that can be used to create CRUD (Create, Read, Update, Delete) endpoints for a Django model. These views provide much functionality out of the box, such as pagination, filtering, and sorting.

Creating CRUD endpoints with viewsets

Viewsets provide a higher-level abstraction than views, allowing you to define a set of related views for a single model or object. Viewsets can handle multiple HTTP methods for the same endpoint, such as GET, POST, PUT, and DELETE. They are a great way to create CRUD endpoints for a Django model quickly.

API Authentication and Permissions

Authentication and permissions are two important concepts in API development. Authentication refers to the process of verifying the identity of a user or client. Permissions refer to determining whether a user or client has the necessary permissions to access a particular resource.

Authentication vs. Authorization

Authentication and authorization are often used interchangeably but are two distinct concepts. Authentication refers to the process of verifying the identity of a user or client. Authorization determines whether a user or client has the necessary permissions to access a particular resource.

Built-in authentication options

Django Rest Framework provides several built-in authentication options, such as TokenAuthentication, SessionAuthentication, and BasicAuthentication. These authentication options can be easily added to any view or viewset.

Custom authentication options

In addition to the built-in authentication options, Django Rest Framework also allows you to create custom authentication options. Custom authentication options can be used to integrate with third-party authentication services or to provide more advanced authentication mechanisms.

Built-in permission options

Django Rest Framework provides several built-in permission options, such as IsAuthenticated, IsAdminUser, and AllowAny. These permission options can be easily added to any view or viewset.

Custom permission options

In addition to the built-in permission options, Django Rest Framework also allows you to create custom permission options. Custom permission options can be used to provide more fine-grained access control or to integrate with third-party authorization systems.

Working with Relationships

In many cases, API endpoints must return related data along with the primary data. Django Rest Framework provides several l options for working with relationships and related data.

Serializing related data

Serializing related data allows you to include data from related models in your response. This is useful when retrieving data from multiple tables in one request. Django Rest Framework provides several options for serializing related data.

One of the options is using the depth attribute in the serializer. The depth attribute specifies the number of deep levels the serializer should traverse when serializing related data. For example, if you have a Book model that has a foreign key relationship with a Publisher model, you can set the depth attribute to 1 in BookSerializer to include the publisher information in the response.

Creating nested serializers

Another option for serializing related data is using nested serializers. Nested serializers allow you to include related data as nested objects within the main object. This provides a more structured response and allows you to control the fields returned for the related data.

For example, if you have a Book model that has a foreign key relationship with a Author model, you can create an AuthorSerializer and include it as a field in the BookSerializer. This will serialize the author's information as a nested object within the book information in the response.

Filtering related data

When working with related data, you may also need to filter the related data based on certain criteria. Django Rest Framework provides several options for filtering related data.

One of the options is using the related_name attribute in the model field. This allows you to specify a custom name for the related field that can be used for filtering.

Another option is using the ForeignKey or ManyToManyField manager to filter related data. For example, suppose you have a Book model with a many-to-many relationship with a Category model. In that case, you can use the categories__name filter to retrieve all books associated with a particular category.

Pagination with related data

When working with large amounts of related data, it may be necessary to paginate the response. Django Rest Framework provides pagination classes that can be used to paginate related data.

To paginate related data, specify the pagination class in the view or viewset that retrieves the related data. For example, if you have a Book the model that has a foreign key relationship with a Publisher model, you can specify the pagination class in the PublisherViewSet to paginate the books associated with the publisher.

Working with Requests and Responses

Django Rest Framework provides several options for processing requests and responses in your API views.

Request object

The request object contains information about the incoming request. This includes the request method, headers, body, and query parameters.

Response object

The response object contains information about the outgoing response. This includes information about the response status code, headers, and body.

Using status codes

HTTP status codes are used to indicate the status of a response. Django Rest Framework provides constants for all HTTP status codes, making it easy to return the appropriate status code in your API views.

Using headers

HTTP headers are used to provide additional information about the request or response. Django Rest Framework provides several options for working with headers in your API views.

Returning errors

When an error occurs in your API view, returning an appropriate error response is important. Django Rest Framework provides several options for returning error responses, including using the built-in APIException class or creating custom exception classes.

Testing Django Rest Framework

Testing is an important part of building a robust and reliable API. Django Rest Framework provides several options for testing your API, including using the built-in test.

Framework in Django.

Writing tests for Django Rest Framework apps can help catch potential bugs and ensure your API functions as expected. Tests can also document your API, showing other developers how your API endpoints should behave.

To write tests for your Django Rest Framework app, you can use Django’s built-in testing framework, which includes test classes and methods that can be used to test views, serializers, and more.

Running tests for Django Rest Framework apps is also straightforward. You can use the standard Django test runner to run your tests, and Django Rest Framework provides additional test classes and helper methods for testing API endpoints.

When testing your API, it’s important to test for edge cases and unexpected behavior. This can include testing for invalid input data, testing for errors and exceptions, and testing for unexpected behavior in your serializers and views.

By testing your API thoroughly, you can ensure that it’s reliable and robust and meets your users' needs.

Deploying Django Rest Framework Apps

Once you’ve built your Django Rest Framework app and tested it thoroughly, you’ll need to deploy it to a production environment so your users can use it.

Configuring production settings can be complex, and there are many factors to consider, including security, performance, and scalability.

When deploying your Django Rest Framework app, some important considerations include setting up a database, collecting static files, serving static files, and configuring production settings such as security and performance optimizations.

You may also need to consider deploying your app to a hosting provider, such as Heroku or AWS, which can provide additional scalability and reliability features.

Conclusion

In this article, we’ve covered the basics of Django Rest Framework, a powerful and flexible framework for building APIs in Django.

We’ve discussed the benefits of using Django Rest Framework, its prerequisites, and how to start building your API using Django Rest Framework.

We’ve also covered key features of Django Rest Framework, including serializers, views and viewsets, authentication and permissions, working with relationships, and testing and deploying your API.

By following the steps and best practices outlined in this article, you can build a robust and reliable API using Django Rest Framework that meets the needs of your users and your organization.

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Azeem Akhtar
Azeem Akhtar

Written by Azeem Akhtar

Python, Machine Learning, Deep Learning, Data Science, Django, Artificial Intelligence

No responses yet

Write a response