1. Blog
  2. Software Development
  3. Diving Into the Django REST Framework
Software Development

Diving Into the Django REST Framework

Claudio Siervi, Python Developer at BairesDev, talks about the coupling of Django and Django Rest Frameworks (DRF) and discusses its robustness and flexibility for building REST APIs.

BairesDev Editorial Team

By BairesDev Editorial Team

BairesDev is an award-winning nearshore software outsourcing company. Our 4,000+ engineers and specialists are well-versed in 100s of technologies.

10 min read

Featured image

By Claudio Siervi Software Engineer at BairesDev

Django is an incredible open-source framework for web development in Python! It includes everything that’s necessary for building a web application and enables developers to start applications from the ground up in minutes. After only a few command lines, the project is set up.

It was primarily designed to build monolithic applications where, generally, all modules and components are coupled, sharing the same codebase and computational memory. However, Django’s architectural design is different from the conventional monolithic frameworks. The Django modules are independent and don’t affect each other (as is possible). The classes and methods that compose its modules do specific things. Thus, it’s easy for developers to understand and for its software community to maintain.

Django Modules: MTV

Django’s main modules are called Model, Template, and View. These three modules are the basis of its architecture, aka MTV architecture.

  • The Model is the layer of the application’s data. With it, we define data structures and rules to store them in the databases. It’s integrated into an ORM system that maps database tables and fields as Python object classes and can be connected to a range of database systems, thus, seizing object-oriented modeling to handle data and query objects from the database with Python code (if you want, raw SQL queries are also permitted).
  • The Template layer refers to the page layouts and their behaviors, data input, data output, and other aspects related to page rendering. This layer is like the application’s front end. It’s responsible for the application’s static code processing, and has its programming language, the Django Template Language (DTL). This template language serves as a bridge between scripts like HTML, CSS, DTL, JavaScript, and others.
  • The View is the layer of data processing. It comprises a data parsing system, a routing system to expose the View class to external access, and a permission system to authenticate a View based on different rules. It plays a role in processing external requests, verifying user permissions to access the route, getting user data from input forms, and returning something as a response, generally, a template containing static code such as HTML.

Django still has many other outstanding features that we would need at least one full article to describe. So, in a very, very general summary, it has the following:

  • A built-in web server ready-to-use for development purposes and already integrated with a database system manager.
  • A database system manager that is already integrated with an SQLite database, which can be changed to other database systems easily.
  • An ORM system that maps the Django Model classes to their corresponding database tables and provides an intuitive way to handle database operations with Python.
  • A cache framework to optimize server processing by automatically storing request responses and enabling quick access to cached data.
  • The Django Admin Site for managing and interacting with the database from a  user-friendly web interface.
  • A permission system for handling access controls, specifying which users or user groups can perform specific actions or access certain parts of the application.

We can develop almost everything with Django, from prototypes to test business models, webchats, and dashboards, to a complete Content Management System (CMS) or a Customer Relationship Management System (CRM).

Some of Django’s Drawbacks

When considering a client-server architecture, Django may seem to lack features specifically for building backend projects and APIs.

But the good news is that Django has a large ecosystem of third-party frameworks to extend its primary functionalities, giving it superpowers never seen before (dramatically speaking). One of these packages is the Django Rest Framework (DRF), aka REST framework, which improves Django’s capabilities for dealing with REST APIs.

I think the REST Framework has been the choice for developing APIs in almost every Django project I have worked on so far. Its additional modules provide a bunch of reusable code for the APIs specifics proposed, such as data parsing, data handling, and other cool features that we’ll explore deeper in the next section.

Django REST Framework at a Glance

The REST Framework package speeds up API development by solving recurrent issues that aren’t in the Django initial proposal, such as data validation and conversion on APIs requests, the parsing of data on JSON, XML, or YAML formats, the pagination of user content on the client side, or even API testing.

In a few words, the most valuable features of DRF, for me, are as follows:

  • Serializer classes – used to validate data structures and transform them into formats that can be rendered into output formats such as JSON, XML, or YAML.
  • Views classes – used for processing incoming requests and returning appropriate responses on API endpoints.
  • Web browsable API – used for exploring, testing, and interacting with the APIs.

Serializer Classes

The main serializer classes on DRF are the Serializer and the ModelSerializer. You can think of these as the Form and ModelForm classes.

However, unlike Django’s Form and ModelForm, the serializer classes are not limited to dealing with form input or HTML output, as they’re used to validate, transform, and reduce complex data structures into simple ones.

(1) The Serializer class is the basis of the other DRF serializers. It is used to validate, transform, and sanitize data based on the serializer fields and optional methods to change its behavior.

This way, a Serializer class can map data structures based on a bunch of field definitions with explicit types, such as CharField, IntegerField, DecimalField, EmailField, ImageField, PrimaryKeyRelatedField, and others.

The optional Serializer methods aren’t implemented by default, so to use them, we must implement these:

  • .to_internal_value() – can be used to change the serialization behavior by validating and converting data before creating a serializer object.
  • .to_representation() – can be used to change the deserialization behavior by converting or appending data before outputting it.
  • .create() – can be used to create a database record from a serializer object.
  • .update() – can be used to update a database record from a serializer object.

(2) The ModelSerializer class extends the previous Serializer class, automatically associating the serializer fields within the Django Model fields and also implementing a few optional serializer methods such as .create() and .update().

That way, the ModelSerializer fields are automatically populated by only defining a base model and describing the names of the fields as declared in the Django Models definitions. The methods already implemented persist data from simple CRUD operations on the database.

View Classes

In Django, a View class is responsible for processing incoming requests and returning proper responses. The main difference between the Django View class and DRF View classes is that Django View focuses on rendering complete web pages with HTML content, while DRF View provides API responses in different formats serving as endpoints for web applications.

This way, the DRF Views are designed to handle dynamic content such as parsing and returning JSON, XML, or YAML responses for API routes. To be clear, to parse XML or YAML content on DRF, we must use its third-party packages, such as djangorestframework-xml and djangorestframework-yaml.

The REST Framework View classes are organized into three main categories called Views, GenericViews, and ViewSets.

  • The View has more flexible classes to build APIs, but that also requires more coding because it doesn’t come with built-in methods.
  • The GenericViews have classes with common operations, such as standard lists and detailed views already implemented.
  • The ViewSets have classes with common RESTful operations already implemented but are also less flexible.

Each category has a different set of classes with reusable code already implemented at different levels of complexity, and we can choose which to use.

In the Views category, we have the APIView class, which is the base of all REST Framework Views, and the @api_view decorator that wraps function-based views into APIView objects.

  • The APIView class offers configuration options for rendering, parsing, authenticating, throttling, content negotiating, and more. However, it doesn’t come with the built-in methods .get(), .post(), .put(), and .delete() already implemented.
  • The @api_view decorator takes a list of HTTP methods allowed and converts the Django function-based Views into APIView objects with respective HTTP methods implemented.

The GenericView category includes the GenericAPIView class, the Concrete Views subcategory, and the MixIns subcategory. It provides pre-built HTTP methods for common API functionalities, thus reducing code duplication.

  • The GenericAPIView class extends the APIView class by adding standard methods for CRUD operations.
  • The Concrete Views subcategory involves specialized classes to handle specific CRUD operations.
  • The MixIns subcategory is used by the Concrete Views but also can be used to extend Views behaviors with specific behaviors and less duplicated code.

The ViewSets category includes the ViewSet, GenericViewSet, ModelViewSet, and ReadOnlyModelViewSet classes. The ViewSets classes register the API endpoints, automatically registering only one main route and not needing explicit registration of each one.

  • The ViewSet class provides a set of actions (not implemented) for CRUD operations, such as create/retrieve/update/destroy.
  • The GenericViewSet provides default implementations for the CRUD actions, thus enabling the creation of REST APIs with less code.
  • The ModelViewSet works straightforwardly with Django models, providing default implementations for all CRUD actions with pagination and filtering.
  • The ReadOnlyModelViewSet provides read-only access to a resource. This is useful for APIs that only allow users to read data, but not to create or modify it.

Web-Browsable API

The Browsable API offers an HTML representation for the application routes, enabling us to access our resources from a web browser. We can even test user authentication policies with that. After developing a View and linking it to an endpoint URL, we can use the Browsable API to inspect and test that view by accessing its exposed route in a web browser.

For instance, below we tried to access the Browsable API page of the endpoint “/view-set/” locally. However, this API endpoint is secured by an authentication level.

Then, to access that API, we must authenticate the user. So, by clicking the Log In button in the upper right corner, we are redirected to the Login page.

  • Generally, the View classes authentication policies are implemented by the injection of DRF’s authentication classes into the DRF View classes or by wrapping View methods that use the @api_view decorator with an authentication decorator.

After authenticating, we can test our API from the webpage.

Conclusion

Django is a package that provides all the basics for web application development, having a broad range of built-in tools, classes, and methods to encourage the clean and quick development of robust and reliable applications. When used along with the Django Rest Framework package, Django has almost all the tools for REST APIs development.

We can even use Django alone to develop backend applications, including REST APIs. However, developing and testing these features that are already in place in DRF takes much more work. Thus, DRF raises backend development productivity. At the same time, it increases the quality of life of the software engineers, giving them a bunch of reusable code already tested by a vast open-source community around it.

Last but not least, as Django and DRF are both Python packages, we can customize our applications with everything the Python language offers. Did you like the article? Leave us a comment.

See you in the next one!

If you enjoyed this article, check out one of our other Python articles.


 

Claudio is a Software Engineer at BairesDev, on a mission to craft reliable applications for valued clients.

BairesDev Editorial Team

By BairesDev Editorial Team

Founded in 2009, BairesDev is the leading nearshore technology solutions company, with 4,000+ professionals in more than 50 countries, representing the top 1% of tech talent. The company's goal is to create lasting value throughout the entire digital transformation journey.

Stay up to dateBusiness, technology, and innovation insights.Written by experts. Delivered weekly.

Related articles

Contact BairesDev
By continuing to use this site, you agree to our cookie policy and privacy policy.