Developing REST API using functions in DRF application views

This post is in continuation with our previous post “Developing first REST API using Django Rest Framework ( DRF )” , in the previous post, we used class “UserInfoView” to write the views for our application “helloapp” , in this post, we will show how you can use functions instead of class to write the views.

Actually, functions are prior to class in Django Rest Framework, but since classes are most widely used, the use of functions in this post to write simple API is just for making your understanding much better with respect to how DRF views works and how those gets mapped to URL.

Since we have explained all the things in our previous post “Developing first REST API using Django Rest Framework ( DRF )” , you can find the code for this post at github https://github.com/lynxbee/drf_api_view_with_function.git and in this post, we will just explain the related changes..

$ vim helloproject/helloapp/views.py
from django.shortcuts import render
from rest_framework import viewsets
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser

from helloproject.helloapp.models import UserInfo
from helloproject.helloapp.serializers import UserInfoSerializer

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def users(request):
    if request.method == 'GET':
        users = UserInfo.objects.all()
        serializer = UserInfoSerializer(users, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = UserInfoSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

@csrf_exempt
def user(request, pk):
    try:
        user = UserInfo.objects.get(pk=pk)
    except UserInfo.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = UserInfoSerializer(user)
        return JsonResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = UserInfoSerializer(user, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

As you can see above, we have defined two functions “users” which just shows the list of all the users and this function doesn’t takes only one argument i.e. http request and second, “user” which takes two arguments, http request and primary key, which is used to identify the single user.

Now, we need to map this views to urls so we can do http GET and http POST to this urls.

$ vim helloproject/helloapp/urls.py
from django.urls import include, path

from helloproject.helloapp import views

urlpatterns = [
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    path('users/', views.users),
    path('user/<int:pk/>', views.user),
]

Notice here, we have declared two api urls, 1. ” http://127.0.0.1:8000/users/ ” mapped to views.py “users” function and “http://127.0.0.1:8000/user/user_primary_key” mapped to “user” function of views.py

Now, run the server and when you visit two API’s http://127.0.0.1:8000/users/ and http://127.0.0.1:8000/user/primary_key/ you will see it showing empty json… lets do some http post of users api using below script,

#!/bin/bash

API_URL="http://192.168.0.106:8000/users/"

username="lynxbee"
email="social(at)lynxbee.com"
age="35"

data="{\"username\":\"$username\",\"email\":\"$email\",\"age\":\"$age\"}"
echo $data

curl -v -k -H "\"Accept: application/json\"" -H "\"Content-Type:application/json\"" -d $data $API_URL

this script does http POST to populate data to API, now lets say you pushed two entries, then you can see the json as,

[{
	"id": 1,
	"username": "lynxbee",
	"email": "social(at)lynxbee.com",
	"age": "35"
}, {
	"id": 2,
	"username": "lynxbee",
	"email": "social(at)lynxbee.com",
	"age": "35"
}]

Now, using our second API to get individual information using primary key, we need to do http GET using individual / second API, type http://192.168.0.106:8000/user/2/

here, as you can see “http://192.168.0.106:8000/user/2/” API is mapped to

path('user/<int:pk/>', views.user)

from urls.py and same is mapped to views.py. notice here, “int:pk” appends to number to the API request i.e. “user/2” as seen above.

2 thoughts on “Developing REST API using functions in DRF application views”

Leave a Comment