avatarJen-Hsuan Hsieh (Sean)

Summary

The provided content outlines the process of creating endpoints for user resource manipulation in a React and Django web application using Django REST Framework (DRF).

Abstract

The article delves into the development of a single-page application (SPA) with React for the frontend and Django as the backend API server. It specifically focuses on Part 4 of a series, which details the creation of endpoints in DRF to handle user resources. The author explains the use of Django's User model, serializers for data serialization, and class-based views such as APIView and ModelViewSet for CRUD operations. The article also includes practical examples of URL patterns, query parameters, and the implementation of serializers and views to create and retrieve users. Additionally, the author provides insights into using Postman for endpoint validation and references external resources for further understanding of DRF's capabilities. The tutorial aims to guide developers through the process of setting up a functional backend for user management, culminating in the ability to create new users and fetch user data through the API.

Opinions

  • The author emphasizes the importance of serializers in DRF for converting model instances to JSON.
  • The use of class-based views is advocated for their ability to encapsulate and simplify complex application logic.
  • The article suggests that using viewsets.ModelViewSet simplifies the creation of endpoints by reducing the need to manually override HTTP methods.
  • The author provides a personal perspective by mentioning their role as a software engineer and inviting feedback on the article, which serves as their learning note.
  • The inclusion of references to external articles indicates the author's view that additional research and learning resources are beneficial for readers.
  • The tutorial is presented as a hands-on guide, with the author's experience shared to facilitate understanding and application of the concepts discussed.

Build Single page application with React and Django Part 4- Create Endpoints to Manipulate Resources

Copy right@A Layman

Introduction

We have talked about some topics for building the React and Django web application in last few weeks.

The target for this week is to understand the process of creating endpoints in DRF (Django REST Framework).

Assume that our target is to create an endpoint for creating and getting users. We will import the User model from django.contrib.auth.models instead of defining a new model.

from django.contrib.auth.models import User

Agenda

This article includes the following topics.

About this series

The target of this series is to build a ReactJS single page application(SPA) with Django API server and deploy on Heroku.

Overview

The roles between endpoints and the database includes models, serializers, views, and urls

URL and Parameters

The URL of requests is consisted of the following parts. There are two types of parameter that could be retrieved.

  • Path parameter
  • Query parameter

In this section, let’s see how to capture them from URL and pass them into the function-based view .

source: https://dev.to/jenhsuan/day-33-of-100daysofcode-review-cors-5hd6

Path parameter

  • urls.py : define the urlspatterns list
from django.urls import path
from . import views
...
urlpatterns = [
    path('getcar/<str:name>/<str:id>', views.carview, name='carview'), 
]
  • views.py : create the view function
from django.http import HttpResponse 
def carview(request, name, id): 
    return HttpResponse("Name:{} UserID:{}".format(name, id)) 

Query parameter

  • urls.py : define the urlspatterns list
from django.urls import path
from . import views
...
urlpatterns = [
    path('getcar/', views.cariew, name='carview'), 
]
  • views.py : create the view function
from django.http import HttpResponse 
def carview(request): 
    name = request.GET['name'] 
    id = request.GET['id'] 
    return HttpResponse("Name:{} UserID:{}".format(name, id)) 

Model manipulation — Serializers

Introduction

The Serializer is responsible to serialize the data to return data with the response. We have to assign two kinds of fields in the class.

1. model

Specify the model for this serializer

2. fields

Specify fields from the model. We can also specify fields from other serializers. It depends on the relationship between models

The example of serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username',)
class UserSerializerWithToken(serializers.ModelSerializer):
    token = serializers.SerializerMethodField()
    password = serializers.CharField(write_only=True)
    class Meta:
        model = User
        fields = ('token', 'username', 'password')
...

Class-based Views — APIview

Introduction

The purpose of the class-based view is to provide a solution for more complicated application logic in a view.

There are a few different types we can use for views in DRF. The first type is APIview.

The example of views.py

There are few things we have to do in these method.

  1. Retrieve the queryset
  2. Specify the serializer
  3. Return the response with data
  4. For APIview, we have to override get, post, put, and delete method. We can set the permission in this class
class UserList(APIView):
    permission_classes = (permissions.AllowAny,)
def get(self, request, format=None):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)
def post(self, request, format=None):
        serializer = UserSerializerWithToken(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The example of urls.py

We have to use as_view method when registering the view in urls.py.

from django.urls import path
from . import views
...
urlpatterns = [
    path('users/', UserList.as_view(), name='users')
]

Validate with Postman

We create an endpoint for creating and getting users successfully

  • Getting users
Copy right@A Layman
  • Creating a new user
Copy right@A Layman

Class-based Views — viewsets.ModelViewSet

Introduction

Using viewsets.ModelViewSet is simpler than using APIview. We don’t have to override methods.

The example of views.py

There are few things we have to do in these classes

  1. Retrieve the queryset
  2. Specify the serializer
  3. Specify http methods
  4. We can set the permission in the class
from .serializers import UserSerializer, UserSerializerWithTokenfrom django.contrib.auth.models import User
from rest_framework import viewsets, permissions
class UserViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.AllowAny,)
    queryset = User.objects.all()
    serializer_class = UserSerializer
    http_method_names = ['get', 'put',]
class UserViewSetForCreatingUser(viewsets.ModelViewSet):
    permission_classes = (permissions.AllowAny,)
    queryset = User.objects.all()
    serializer_class = UserSerializerWithToken
    http_method_names = ['post']

The example of urls.py

We have to use router for registering viewset with the same prefix

from django.urls import include
from django.conf.urls import url
from .views import UserViewSetForCreatingUser, UserViewSet
from rest_framework.routers import DefaultRouter
...
router = DefaultRouter()
router.register(r'user', UserViewSet)
router.register(r'createuser', UserViewSetForCreatingUser)
urlpatterns = [
    url(r'^api/', include(router.urls)),
]

Validate with Postman

We create an endpoint for creating and getting users successfully

  • Getting users
Copy right@A Layman
  • Creating a new user
Copy right@A Layman

References

Summary

Thanks for your patient. I am Sean. I work as a software engineer.

This article is my note. Please feel free to give me advice if any mistakes. I am looking forward to your feedback.

Please feel free to clap if this article can help you. Thank you.

You can also subscribe my page on Facebook.

Related topics

How to use the two-way binding in Knout.js and ReactJS?

Learn how to use SignalR to build a chatroom application

My reflection of :

IT & Network:

Database:

Software testing:

Debugging:

DevOps:

Django
Rest
API
Software Development
Python
Recommended from ReadMedium