REST API Using Django Rest Framework
REST API Using Django Rest Framework
API (Application Programming Interface) is a way to manage data across different devices.
This note focuses on APIs built using Django Rest Framework.
Key points:
Serializer creation:
Example:
\
SerializerMethodField and Validate Methods in Django Rest Framework
1. SerializerMethodField
SerializerMethodField is a special field in Django Rest Framework serializers. It's used when
you want to include data in your serialized output that doesn't directly correspond to a model
field.
Key points:
Example:
SerializerMethodField is like a custom calculator in our API waiter's toolkit. It can create new
information based on existing data. For example, it can combine a person's first and last
name to create a full name, even if 'full_name' isn't a field in our database.
2. Validate Methods
Validate methods in serializers are used to add custom validation logic to your fields or the
entire object.
a. Field-level validation:
Example:
b. Object-level validation:
Example:
Validate methods are like security guards for our data. They check if the data is correct
before allowing it into our system.
1. Basic Concept
Object-level validation allows you to validate multiple fields together or perform complex
validation that depends on more than one field. This is done using the validate() method
in your serializer class.
Example:
2. Advanced Usage
a. Accessing context: The validate() method can access the serializer's context, which
can be useful for validations that need additional information.
b. Modifying data: You can modify the data in the validate() method before returning it.
3. Related Concepts
A. Validators: For reusable validation logic, you can create custom validator functions.
D. Nested serializers: When using nested serializers, validation is applied to each nested
object as well.
Depth in Django Rest Framework Serializers
1. Basic Concept
The 'depth' option in Django Rest Framework serializers is used to control how many levels
of nested serialization should occur. It's a simple way to automatically serialize related
objects to a certain level without having to explicitly define nested serializers.
You can set the depth in the Meta class of your serializer:
In this example, 'depth = 1' means that the 'books' field (assuming it's a related field) will be
serialized one level deep.
3. Depth Levels
● depth = 0 (default): No nested serialization occurs.
● depth = 1: First level of related objects are serialized.
● depth = 2: First and second levels of related objects are serialized.
● And so on...
4. Example with Multiple Levels
Views
Example:
3. Generic Views
DRF provides a set of pre-built views for common operations. These include:
Example:
● Generic views are more granular. You typically use one view class per
endpoint.
● ViewSets group related views together and use "actions" to define
behavior.
● Generic views map directly to HTTP methods, while ViewSet actions
are typically mapped to HTTP methods in the URL router.
● Generic views are focused on a single type of operation, while ViewSets
combine multiple operations.
Example:
This view will return a list of all books in the database.
Example:
Example:
This view will return details of a specific book when given its primary key.
Example:
Example:
Example:
This view will allow listing all posts and creating new ones.
Example:
This view will allow retrieving details of a product and updating it.
h. RetrieveDestroyAPIView: This view combines RetrieveAPIView and
DestroyAPIView, allowing reading and deleting a single instance.
Example:
This view will allow retrieving details of an order and deleting it.
Example:
This view will allow retrieving, updating, and deleting a specific article.
These Generic Views significantly reduce the amount of code you need to
write for common operations in your API. They encapsulate the logic for
different HTTP methods (GET, POST, PUT, DELETE) and provide a consistent
interface for working with your models. By using these views, you can quickly
set up CRUD (Create, Read, Update, Delete) operations for your models with
minimal code.
4.ViewSets
ViewSets in DRF are classes that combine the logic for multiple related
views in a single class. They provide actions for standard list, create,
retrieve, update, and delete operations.
Key points:
Types of ViewSets
1. ViewSet
2. GenericViewSet
3. ModelViewSet
4. ReadOnlyModelViewSet
1. ViewSet
This is the base class for all ViewSet types. It doesn't provide any actions by
default.
Example:
Real-life scenario: A dashboard ViewSet that provides various statistics and
doesn't directly correspond to a single model.
2. GenericViewSet
Inherits from GenericAPIView and provides the base functionality for other
ViewSets. It doesn't include any actions by default.
Example:
Example:
Real-life scenario: A CRM system where you need full CRUD operations for
customer data.
4. ReadOnlyModelViewSet
Example:
Real-life scenario: A blog where you want to expose published posts for
reading, but not allow editing or creating posts through the API.
Actions for viewsets
ModelViewSet specifics:
Custom ViewSets:
Action mapping:
Custom actions allow you to add additional endpoints to your ViewSet beyond
the standard create, retrieve, update, and delete operations.
Mixins
Purpose of Mixins:
1. rest_framework.views.APIView
2. rest_framework.viewsets.GenericViewSet
3. rest_framework.generics.GenericAPIView
4. Any custom class-based views you create
It includes:
● CreateModelMixin
● RetrieveModelMixin
● UpdateModelMixin
● DestroyModelMixin
● ListModelMixin
● GenericViewSet
● With APIView: You typically wouldn't use the standard DRF model mixins.
Instead, you'd implement the methods yourself or use custom mixins that
don't rely on GenericAPIView's functionality.
● With custom views (like the Django View class): Again, the standard DRF
model mixins aren't suitable. You'd use custom mixins or implement the
functionality directly.
● The standard DRF mixins (CreateModelMixin, ListModelMixin, etc.) are
designed to work with GenericAPIView, not with the basic APIView or custom
views. This is because these mixins depend on certain methods and attributes
provided by GenericAPIView.
● The standard DRF mixins (CreateModelMixin, ListModelMixin, etc.) are
designed to work with classes that provide the functionality of
GenericAPIView, which includes both GenericAPIView itself and its
subclasses like GenericViewSet.
Key difference in usage:
● With GenericAPIView, you typically need to define the HTTP method handlers
(get, post, etc.) explicitly.
● With GenericViewSet, the viewset's as_view() method automatically maps
actions to HTTP methods based on the included mixins.
1. With APIView
APIView is the base class for views in DRF. Mixins can be used to add specific
functionalities.
2. With GenericAPIView
GenericAPIView extends APIView with common behavior for standard list and detail
views.
3. With ViewSets
ViewSets combine the logic for multiple related views in a single class.
QuerySet
● A queryset is a collection of database objects from your Django models.
It represents a database query but doesn't fetch the data until it's
needed.
● In DRF, the queryset attribute is used to specify which objects should be
used for CRUD operations in your API views.
● How is it implemented? It's typically set as a class attribute in your view:
What's its purpose?
Limitations:
get_queryset():
● Get_queryset is a method that returns a queryset of objects to be used
in the view.
● It's used to dynamically generate the queryset based on the current
request or other factors.
● How is it implemented? Override the get_queryset() method in your
view:
When to use:
These two work with various DRF generic views and viewsets. Let me clarify
this for you:
● ListAPIView
● RetrieveAPIView
● CreateAPIView
● UpdateAPIView
● DestroyAPIView
● ListCreateAPIView
● RetrieveUpdateAPIView
● RetrieveDestroyAPIView
● RetrieveUpdateDestroyAPIView
2. ViewSets:
● ModelViewSet
● ReadOnlyModelViewSet
All these views can use both the queryset attribute and the get_queryset()
method.
EXAMPLES :
In these examples:
● The queryset attribute sets the base queryset for the view.
● The get_queryset() method allows you to customise the queryset
dynamically, often based on the current request.
● For create operations, while queryset isn't directly used, it can still
be useful for permissions and other DRF features.
Filtering in DRF allows you to restrict the results of a query based on certain
criteria. It enables clients to request specific subsets of data that match given
conditions.
DRF allows you to combine ordering and filtering, providing powerful data
manipulation capabilities to API clients.
Implementation:
This setup allows for searching across title and author fields:
The search will look for partial matches in both title and author fields.
Permissions
Custom Permissions
Permission Checks:
● For views: Occurs before any other code in the view runs
● For objects: Occurs after the view's queryset has been filtered
Applying Permissions:
● Globally: In settings.py
Custom permission
Custom Permissions in Django Rest Framework
b. Basic Structure:
Key Methods in Custom Permissions a. has_permission(self, request, view)
a. Role-Based Permission:
c. Time-Based Permission:
Custom Permissions in ViewSets
Purpose of Routers:
DefaultRouter Features:
Customizing Routes: You can customize routes using the @action decorator in
your ViewSet:
Authentication
Authentication in DRF
Authentication is the process of verifying the identity of a user or system making a
request to an API. In DRF, it determines if a request should be permitted and
identifies the requester.
Types of Authentication
1. Basic Authentication
2. Session Authentication
3. Token Authentication
4. JWT Authentication
5. Custom Authentication
Detailed Explanation of Each Type
1. Basic Authentication
○ Uses HTTP Basic Auth
○ Sends credentials with each request
○ Implementation:
Logic:
Logic:
Logic:
Logic:
Logic: