Django REST framework (DRF) is a powerful and flexible toolkit for building web APIs. In this tutorial, we’ll learn how to build a CRUD API in just 15 minutes using the Django REST framework PUT is a part of It

To build our sample to-do list application, we’ll start by setting up the Django REST framework in a Django project, followed by a complete tutorial on how to create a CRUD REST API with the Django REST framework.

Use my previous article to know about Get Method and Post Method

Use Previous project or Create a Django project called drinks with the following command

django-admin startproject drinks

Then, cd into the new drinks folder and create a new app for your API

python manage.py startapp core

Run your initial migrations of the built-in user model:

python manage.py migrate

Next, add rest_framework and drinks to the INSTALLED_APPS inside the settings.py file:

# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'core'
]

Create a model in models.py file like

from django.db import models

# Create your models here.


class Drink(models.Model):
  name=models.CharField(max_length=200)
  description = models.CharField(max_length=500)


  def __str__(self):
    return self.name+" "+self.description

Then apply Commands and Create a SuperUser to Our project:

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

Model serializer

To convert the Model object to an API-appropriate format like JSON, Django REST framework uses the ModelSerializer class to convert any model to serialized JSON objects:

from rest_framework import serializers
from .models import Drink

class DrinkSerializer(serializers.ModelSerializer):
  class Meta:
    model= Drink
    fields = '__all__'

Put Method

In this section, we’ll walk through how to create two API views, detail view with the the primary key.

The PUT() method fetches the to-do object if it is available in the database, updates its data with requested data, and saves the updated data in the database.

In order to update objects, we can use POST requests, targeting a certain id. Then, we can retrieve that object, update it and save it under the same id – persisting the change

However, you typically won’t be using POST requests for this – even though you can. To decouple creation and update logic – we use PUT requests to, well, patch existing resources and change them.

The APIView class provides us with the patch()  Or put( ) function – which handles PATCH requests and updates the data.

Creating API Views in Django

class drink_detail(APIView):

    def put(self, request, id=None):

        drinks = Drink.objects.filter(id=id)
        serializer = DrinkSerializer(drinks, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

Pay close attention to this line:

serializer = DrinkSerializer(item, data=request.data,partial=True)

Here we are passing three arguments to our serializer.

  • The instance of the Drink model that we want to update.
  • The data received from the request.
  • partial=True to indicate that this may not contain all the fields of our model Drink.

Since we need to pass in an actual instance, we’ll have to use the get() function to first retrieve a resource and then update it.

Run the Django server:

python manage.py runserver

Now, we’re ready for the first test. Navigate to http://127.0.0.1:8000. Make sure you’re logged in with your superuser credentials:

Now Consider 3rd Object and Update Mango to Strawberry to do that

Run the Command to get Only that particular record using getMethod in DetailedView

http://127.0.0.1:8000/3

The Output we will get is

Now Change the Name Mango Soda to Strawberry Soda and hit the Put Button then the Output will come

Conclusion

Congratulations! You’ve successfully built your first fully functional CRUD Django REST API.

Building a RESTful API can be complicated, but Django REST framework handles complexity fairly well. I hope you have fun building new APIs using the Django REST framework, and be sure to leave a comment if you have any questions. Happy coding!