In the world of web development, the PUT method plays a crucial role in updating existing resources or creating them if they don’t already exist. In the context of API”s, the PUT method is commonly used to modify or replace an existing resource’s data on the server. In this blog, we will dive into the PUT method in Django Rest Framework (DRF) and provide a practical example to illustrate its usage.
Read our New Blog on How to Combine all API Methods like Get, Post, Put, Delete in One View
The PUT Method in Django Rest Framework
The PUT method in Django Rest Framework is designed to handle updates or replacements of resources. When a client sends a PUT request to the server, it includes the updated data for a specific resource, and the server uses that data to update the resource’s state accordingly. If the resource with the specified identifier (typically the primary key) doesn’t exist, the server may create a new resource using the provided data.
DRF streamlines the handling of PUT requests by providing built-in functionality for processing the update data and validating it using serializers. This allows developers to focus on the business logic while DRF takes care of data validation and updates.
Prerequisites:
Before we begin, ensure you have the following prerequisites in place:
- Django installed on your system.
- Basic familiarity with Django project structure and database concepts.
- Virtual Environment, this is optional but recommended. You check our blog here.
Note: For this tutorial, we are using our basic skeleton project for Django. You can also download the project from here.
Sample Django Model and Serializers for Examples
Step 1: Create the Django Model
First, define the Django model that represents a book. In your app’s models.py
, add the following code:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()
Don’t forget to run python manage.py makemigrations
and python manage.py migrate
to create the corresponding database table for the model.
Step 2: Create the Serializer
Next, create a serializer to convert the book model instances into JSON data and vice versa. In your app’s serializers.py
, add the following code:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['id', 'title', 'author', 'publication_date']
1. Implementing a Django Rest Framework API with the PUT Method
Let’s create a simple API to manage a collection of books and demonstrate how the PUT method works. For this example, we assume that you already have Django and Django Rest Framework installed in your project.
Step 1: Create the View
Now, create a view to handle PUT requests for updating existing books object. In your app’s views.py
, add the following code:
from rest_framework import generics
from .models import Book
from .serializers import BookSerializer
class BookUpdateView(generics.UpdateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
Step 2: Define the URL Pattern
Finally, define a URL pattern to map the view with a URL endpoint that includes the unique identifier (in this case, the book’s id
). In your project’s urls.py
, add the following code:
from django.urls import path
from .views import BookUpdateView
urlpatterns = [
path('api/books/<int:pk>/', BookUpdateView.as_view(), name='book-update'),
]
Step 3: Test the API with the PUT Method
With the API set up, you can now test the PUT method to update an existing book. Use tools like curl
or Postman to send a PUT request to the URL http://localhost:8000/api/books/<book_id>/
with the updated book data in the request body.
For example, using curl
, you can update the book with id=1
with the following command:
curl -X PUT -H "Content-Type: application/json" -d '{"title":"Updated Book","author":"Jane Doe","publication_date":"2023-08-15"}' http://localhost:8000/api/books/1/
The server will process the data and update the book with the provided information. If successful, it will respond with a JSON representation of the updated book.
Conclusion
In this blog post, we explored the PUT method in Django Rest Framework, which is used to update or replace existing resources in the API. We walked through a step-by-step example of creating a simple API to manage books, covering model creation, serializer definition, view creation, and URL configuration. DRF’s built-in features make it easy to handle data validation, updates, and resource modifications, providing a powerful foundation for building web applications that can efficiently manage and update data on the server.
Find this tutorial on Github.