Djnago Rest Framework(DRF)

Categories: Beginner, Web API
Wishlist Share
Share Course
Page Link
Share On Social Media

About Course

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Some reasons you might want to use REST framework:


Funding

REST framework is a collaboratively funded project. If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.

Every single sign-up helps us make REST framework long-term financially sustainable.

Many thanks to all our wonderful sponsors, and in particular to our premium backers, SentryStreamSpacinovRetoolbit.ioPostHogCryptAPIFEZTOSvix, , and Zuplo.


Requirements

REST framework requires the following:

  • Django (4.2, 5.0, 5.1)
  • Python (3.8, 3.9, 3.10, 3.11, 3.12, 3.13)

We highly recommend and only officially support the latest patch release of each Python and Django series.

The following packages are optional:

  • PyYAMLuritemplate (5.1+, 3.0.0+) – Schema generation support.
  • Markdown (3.3.0+) – Markdown support for the browsable API.
  • Pygments (2.7.0+) – Add syntax highlighting to Markdown processing.
  • django-filter (1.0.1+) – Filtering support.
  • django-guardian (1.1.1+) – Object level permissions support.

Installation

Install using pip, including any optional packages you want…

pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support

…or clone the project from github.

git clone https://github.com/encode/django-rest-framework

Add 'rest_framework' to your INSTALLED_APPS setting.

INSTALLED_APPS = [
    ...
    'rest_framework',
]

If you’re intending to use the browsable API you’ll probably also want to add REST framework’s login and logout views. Add the following to your root urls.py file.

urlpatterns = [
    ...
    path('api-auth/', include('rest_framework.urls'))
]

Note that the URL path can be whatever you want.

Example

Let’s take a look at a quick example of using REST framework to build a simple model-backed API.

We’ll create a read-write API for accessing information on the users of our project.

Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK. Start off by adding the following to your settings.py module:

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

Don’t forget to make sure you’ve also added rest_framework to your INSTALLED_APPS.

We’re ready to create our API now. Here’s our project’s root urls.py module:

from django.urls import path, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'is_staff']

# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

You can now open the API in your browser at http://127.0.0.1:8000/, and view your new ‘users’ API. If you use the login control in the top right corner you’ll also be able to add, create and delete users from the system.

Show More

What Will You Learn?

  • Master Django fundamentals and advanced concepts
  • Learn to build dynamic web applications using Django
  • Understand Django's MTV (Model-Template-View) architecture
  • Work with Django ORM for database interactions
  • Implement authentication and authorization in Django
  • Deploy Django applications on production servers

Course Content

Requests
If you're doing REST-based web service stuff ... you should ignore request.POST. — Malcom Tredinnick, Django developers group REST framework's Request class extends the standard HttpRequest, adding support for REST framework's flexible request parsing and request authentication. Request parsing REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data. .data request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes except that: It includes all parsed content, including file and non-file inputs. It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH requests. It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data similarly to how you handle incoming form data. For more details see the parsers documentation. .query_params request.query_params is a more correctly named synonym for request.GET. For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests. .parsers The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Parser instances, based on the parser_classes set on the view or based on the DEFAULT_PARSER_CLASSES setting. You won't typically need to access this property. Note: If a client sends malformed content, then accessing request.data may raise a ParseError. By default REST framework's APIView class or @api_view decorator will catch the error and return a 400 Bad Request response. If a client sends a request with a content-type that cannot be parsed then a UnsupportedMediaType exception will be raised, which by default will be caught and return a 415 Unsupported Media Type response. Content negotiation The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types. .accepted_renderer The renderer instance that was selected by the content negotiation stage. .accepted_media_type A string representing the media type that was accepted by the content negotiation stage. Authentication REST framework provides flexible, per-request authentication, that gives you the ability to: Use different authentication policies for different parts of your API. Support the use of multiple authentication policies. Provide both user and token information associated with the incoming request. .user request.user typically returns an instance of django.contrib.auth.models.User, although the behavior depends on the authentication policy being used. If the request is unauthenticated the default value of request.user is an instance of django.contrib.auth.models.AnonymousUser. For more details see the authentication documentation. .auth request.auth returns any additional authentication context. The exact behavior of request.auth depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against. If the request is unauthenticated, or if no additional context is present, the default value of request.auth is None. For more details see the authentication documentation. .authenticators The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Authentication instances, based on the authentication_classes set on the view or based on the DEFAULT_AUTHENTICATORS setting. You won't typically need to access this property. Note: You may see a WrappedAttributeError raised when calling the .user or .auth properties. These errors originate from an authenticator as a standard AttributeError, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the AttributeError originates from the authenticator and will instead assume that the request object does not have a .user or .auth property. The authenticator will need to be fixed. Browser enhancements REST framework supports a few browser enhancements such as browser-based PUT, PATCH and DELETE forms. .method request.method returns the uppercased string representation of the request's HTTP method. Browser-based PUT, PATCH and DELETE forms are transparently supported. For more information see the browser enhancements documentation. .content_type request.content_type, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided. You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior. If you do need to access the content type of the request you should use the .content_type property in preference to using request.META.get('HTTP_CONTENT_TYPE'), as it provides transparent support for browser-based non-form content. For more information see the browser enhancements documentation. .stream request.stream returns a stream representing the content of the request body. You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior. Standard HttpRequest attributes As REST framework's Request extends Django's HttpRequest, all the other standard attributes and methods are also available. For example the request.META and request.session dictionaries are available as normal. Note that due to implementation reasons the Request class does not inherit from HttpRequest class, but instead extends the class using composition.

  • Request parsing
    04:26
  • Content negotiation
    09:24
  • Django Rest Framework
  • Django Rest Framework(Requests)

Responses
Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process. — Django documentation REST framework supports HTTP content negotiation by providing a Response class which allows you to return content that can be rendered into multiple content types, depending on the client request. The Response class subclasses Django's SimpleTemplateResponse. Response objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. There's no requirement for you to use the Response class, you can also return regular HttpResponse or StreamingHttpResponse objects from your views if required. Using the Response class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats. Unless you want to heavily customize REST framework for some reason, you should always use an APIView class or @api_view function for views that return Response objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view. Creating responses Response() Signature: Response(data, status=None, template_name=None, headers=None, content_type=None) Unlike regular HttpResponse objects, you do not instantiate Response objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives. The renderers used by the Response class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the Response object. You can use REST framework's Serializer classes to perform this data serialization, or use your own custom serialization. Arguments: data: The serialized data for the response. status: A status code for the response. Defaults to 200. See also status codes. template_name: A template name to use if HTMLRenderer is selected. headers: A dictionary of HTTP headers to use in the response. content_type: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly. Attributes .data The unrendered, serialized data of the response. .status_code The numeric status code of the HTTP response. .content The rendered content of the response. The .render() method must have been called before .content can be accessed. .template_name The template_name, if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response. .accepted_renderer The renderer instance that will be used to render the response. Set automatically by the APIView or @api_view immediately before the response is returned from the view. .accepted_media_type The media type that was selected by the content negotiation stage. Set automatically by the APIView or @api_view immediately before the response is returned from the view. .renderer_context A dictionary of additional context information that will be passed to the renderer's .render() method. Set automatically by the APIView or @api_view immediately before the response is returned from the view. Standard HttpResponse attributes The Response class extends SimpleTemplateResponse, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way: response = Response() response['Cache-Control'] = 'no-cache' .render() Signature: .render() As with any other TemplateResponse, this method is called to render the serialized data of the response into the final response content. When .render() is called, the response content will be set to the result of calling the .render(data, accepted_media_type, renderer_context) method on the accepted_renderer instance. You won't typically need to call .render() yourself, as it's handled by Django's standard response cycle.

Class-based Views
Django's class-based views are a welcome departure from the old-style views. — Reinout van Rees REST framework provides an APIView class, which subclasses Django's View class. APIView classes are different from regular View classes in the following ways: Requests passed to the handler methods will be REST framework's Request instances, not Django's HttpRequest instances. Handler methods may return REST framework's Response, instead of Django's HttpResponse. The view will manage content negotiation and setting the correct renderer on the response. Any APIException exceptions will be caught and mediated into appropriate responses. Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method. Using the APIView class is pretty much the same as using a regular View class, as usual, the incoming request is dispatched to an appropriate handler method such as .get() or .post(). Additionally, a number of attributes may be set on the class that control various aspects of the API policy. For example: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User class ListUsers(APIView): """ View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. """ authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAdminUser] def get(self, request, format=None): """ Return a list of all users. """ usernames = [user.username for user in User.objects.all()] return Response(usernames) Note: The full methods, attributes on, and relations between Django REST Framework's APIView, GenericAPIView, various Mixins, and Viewsets can be initially complex. In addition to the documentation here, the Classy Django REST Framework resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.

Generic views
Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself. — Django Documentation One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns. The generic views provided by REST framework allow you to quickly build API views that map closely to your database models. If the generic views don't suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.

Student Ratings & Reviews

No Review Yet
No Review Yet