Instagram
youtube
Facebook
Twitter

Function Based API View

In this tutorial, we’ll learn about function-based API views in the Django REST framework. We will cover topics including creating API views, handling different HTTP methods, and testing the API.

  • In this tutorial, we will create a simple API to manage student records that we have created in our previous tutorials using Django REST Framework.

  • We will perform CRUD operations on the Students model, allowing us to create, retrieve, update, and delete student records through API endpoints.

Django Models Setup

We have already created an students model to save student's data including name, roll number and city. But, if you haven't gone through the previous tutorial we are again mentioning the model below.

from django.db import models

# Create your models here.
class Students(models.Model):
    Name = models.CharField(max_length=50)
    Roll = models.IntegerField()
    City = models.CharField(max_length=100)

    def __str__(self): 
     return self.Name

Don't forget to run migrations to create the database table.

Create Serializers

In serializers.py file create a serializer for the 'students' model.

from rest_framework import serializers
from .models import Students

class StudentsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Students
        fields = '__all__'

The StudentsSerializer class from Django REST Framework defines how the Students model's data should be converted between Python objects and JSON format. By specifying the model and using '__all__' as fields, it includes all model fields for serialization.

Create API Views

In views.py file we'll create api views to perform 'GET' and 'POST' operations.

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Students
from .serializers import StudentsSerializer

@api_view(['GET', 'POST'])
def student_list(request):
    if request.method == 'GET':
        students = Students.objects.all()
        serializer = StudentsSerializer(students, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = StudentsSerializer(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)

This views.py file handles both 'GET' and 'POST' HTTP requests for a Students model.

When a GET request is made, it retrieves all student records, serializes them using the StudentsSerializer, and returns the serialized data.

For a POST request, it validates the incoming data using the serializer, saves a new student record if valid, and returns the serialized data with an appropriate HTTP status code.

URL Routing

In urls.py file define the URL patterns for the API views.

from django.urls import path
from .views import student_list

urlpatterns = [
    path('students/', student_list, name='student-list'),
]

We've done all the things necessary for creating API views. Now, let's check if our API view is properly working or not by starting the development server using the python manage.py runserver command.

We can use tools like curl, httpie, or API testing tools like Postman to test the API. We'll cover API testing deeply in upcoming tutorials.