Django: POST, PUT, GET, DELETE requests example | Rest Apis

Rest Apis are so important in most applications to connect the backend and frontend parts. In this tutorial, I will show you how to build Python Rest Api CRUD with sending GET/POST/PUT/DELETE requests example using Django REST framework – a powerful and flexible framework for building Web APIs.

You can find how to make it works with database in one of following posts:
Django Rest Api with MySQL example | Django Rest Framework
Django Rest Api with MongoDB example | Django Rest Framework
Django Rest Api with PostgreSQL example | Django Rest Framework

Django Rest Api application Overview

We will build a Django Rest Apis Application that can create, retrieve, update, delete and find Tutorials by title or published status.

The following table shows overview of the Rest APIs that will be exported:

Methods Urls Actions
GET api/tutorials get all Tutorials
GET api/tutorials/:id get Tutorial by id
POST api/tutorials add new Tutorial
PUT api/tutorials/:id update Tutorial by id
DELETE api/tutorials/:id remove Tutorial by id
DELETE api/tutorials remove all Tutorials
GET api/tutorials/published find all published Tutorials
GET api/tutorials?title=[kw] find all Tutorials which title contains 'kw'

And the code for API Views will look like this-

@api_view(['GET', 'POST', 'DELETE'])
def tutorial_list(request):
    # GET list of tutorials, POST a new tutorial, DELETE all tutorials
@api_view(['GET', 'PUT', 'DELETE'])
def tutorial_detail(request, pk):
    # find tutorial by pk (id) 
    # GET / PUT / DELETE tutorial
def tutorial_list_published(request):
    # GET all published tutorials

Why Django REST Framework?

There are many frameworks for building REST APIs, but we’re gonna use the Django Rest Framework by the following reasons:

Django Rest Api Architecture

Let’s look at the architecture of our Django Rest Apis App:


  • HTTP requests will be matched by Url Patterns and passed to the Views
  • Views processes the HTTP requests and returns HTTP responses (with the help of Serializer)
  • Serializer serializes/deserializes data model objects
  • Models contains essential fields and behaviors for CRUD Operations with Database

Step by step to implement Django Rest Api

First, we setup Django Project. Next, we create Rest Api app, add it with Django Rest Framework to the project. Next, we define data model and migrate it to the database. Then we write API Views and define Routes for handling all CRUD operations (including custom finder).

Finally, we’re gonna test the Rest Apis using Postman.

1. Technology

  • Python 3.7
  • Django 2.1.15
  • Django Rest Framework 3.11.0
  • django-cors-headers 3.2.1

2. Project structure


Let me explain it briefly.

  • tutorials/ declares TutorialsConfig class (subclass of django.apps.AppConfig) that represents Rest CRUD Apis app and its configuration.
  • DjangoRestApi/ contains settings for our Django project: Database engine, INSTALLED_APPS list with Django REST framework, Tutorials Application, CORS and MIDDLEWARE.
  • tutorials/ defines Tutorial data model class (subclass of django.db.models.Model).
  • migrations/ is created when we make migrations for the data model, and will be used for generating database table.
  • tutorials/ manages serialization and deserialization with TutorialSerializer class (subclass of rest_framework.serializers.ModelSerializer).
  • tutorials/ contains functions to process HTTP requests and produce HTTP responses (using TutorialSerializer).
  • tutorials/ defines URL patterns along with request functions in the Views.
  • DjangoRestApi/ also has URL patterns that includes tutorials.urls, it is the root URL configurations.

3. Install Django REST framework

Django REST framework helps us to build RESTful Web Services flexibly.

To install this package, run command:
pip install djangorestframework

4. Setup new Django project

Let’s create a new Django project with command:
django-admin startproject DjangoRestApi

When the process is done, you can see folder tree like this:


Now we open and add Django REST framework to the INSTALLED_APPS array here.

    # Django REST framework 

5. Setup new Django app for CRUD Rest Api

Run following commands to create new Django app tutorials:

cd DjangoRestApi
python startapp tutorials

Refresh the project directory tree, you can see it now looks like:


Now open tutorials/, you can see TutorialsConfig class (subclass of django.apps.AppConfig).
This represents the Django app that we’ve just created with its configuration:

from django.apps import AppConfig

class TutorialsConfig(AppConfig):
    name = 'tutorials'

Don’t forget to add this app to INSTALLED_APPS array in

    # Tutorials application 

6. Configure CORS for a Rest Api Resource

Cross-Origin Resource Sharing (CORS) is a protocol that enables scripts running on a browser client to interact with resources from a different origin.

In this example, we’re gonna configure CORS to accept requests from localhost:8081, for example.

First, install the django-cors-headers library:
pip install django-cors-headers

In, add configuration for CORS:

    # CORS

You also need to add a middleware class to listen in on responses:

    # CORS

Note: CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as CommonMiddleware.


  • CORS_ORIGIN_ALLOW_ALL: If True, all origins will be accepted (not use the whitelist below). Defaults to False.
  • CORS_ORIGIN_WHITELIST: List of origins that are authorized to make cross-site HTTP requests. Defaults to [].

7. Define the Django REST framework Model

Open tutorials/, add Tutorial class as subclass of django.db.models.Model.
There are 3 fields: title, description, published.

from django.db import models

class Tutorial(models.Model):
    title = models.CharField(max_length=70, blank=False, default='')
    description = models.CharField(max_length=200,blank=False, default='')
    published = models.BooleanField(default=False)

Each field is specified as a class attribute, and each attribute maps to a database column.
id field is added automatically.

8. Migrate Data Model to the database

Run the Python script: python makemigrations tutorials.

The console will show:

Migrations for 'tutorials':
    - Create model Tutorial

Refresh the workspace, you can see new file tutorials/migrations/
It includes code to create Tutorial data model:

# Generated by Django 2.1.15

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [

    operations = [
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(default='', max_length=70)),
                ('description', models.CharField(default='', max_length=200)),
                ('published', models.BooleanField(default=False)),

The generated code defines Migration class (subclass of the django.db.migrations.Migration).
It has operations array that contains operation for creating Customer model table: migrations.CreateModel().

The call to this will create a new model in the project history and a corresponding table in the database to match it.

To apply the generated migration above, run the following Python script:
python migrate tutorials

The console will show:

Operations to perform:
  Apply all migrations: tutorials
Running migrations:
  Applying tutorials.0001_initial... OK

9. Create Serializer class for Data Model

Let’s create TutorialSerializer class that will manage serialization and deserialization from JSON.

It inherit from rest_framework.serializers.ModelSerializer superclass which automatically populates a set of fields and default validators. We need to specify the model class here.


from rest_framework import serializers 
from tutorials.models import Tutorial
class TutorialSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tutorial
        fields = ('id',

In the inner class Meta, we declare 2 attributes:

  • model: the model for Serializer
  • fields: a tuple of field names to be included in the serialization

10. Define Django REST framework Routes

When a client sends request to our Django Rest Api for an endpoint using HTTP request (GET, POST, PUT, DELETE), we need to determine how the server will response by defining the routes.

These are our routes:

  • /api/tutorials: GET, POST, DELETE
  • /api/tutorials/:id: GET, PUT, DELETE
  • /api/tutorials/published: GET

Create a inside tutorials app with urlpatterns containing urls to be matched with request functions in the

from django.conf.urls import url 
from tutorials import views 
urlpatterns = [ 
    url(r'^api/tutorials$', views.tutorial_list),
    url(r'^api/tutorials/(?P<pk>[0-9]+)$', views.tutorial_detail),
    url(r'^api/tutorials/published$', views.tutorial_list_published)

Don’t forget to include this URL patterns in root URL configurations.
Open DjangoRestApi/ and modify the content with the following code:

from django.conf.urls import url, include 
urlpatterns = [ 
    url(r'^', include('tutorials.urls')),

11. Write Django REST framework API Views

We’re gonna create these API functions for CRUD Operations:
tutorial_list(): GET list of tutorials, POST a new tutorial, DELETE all tutorials
tutorial_detail(): GET / PUT / DELETE tutorial by ‘id’
tutorial_list_published(): GET all published tutorials

Open tutorials/ and write following code:

from django.shortcuts import render

from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser 
from rest_framework import status
from tutorials.models import Tutorial
from tutorials.serializers import TutorialSerializer
from rest_framework.decorators import api_view

@api_view(['GET', 'POST', 'DELETE'])
def tutorial_list(request):
    if request.method == 'GET':
        tutorials = Tutorial.objects.all()
        title = request.query_params.get('title', None)
        if title is not None:
            tutorials = tutorials.filter(title__icontains=title)
        tutorials_serializer = TutorialSerializer(tutorials, many=True)
        return JsonResponse(, safe=False)
        # 'safe=False' for objects serialization
    elif request.method == 'POST':
        tutorial_data = JSONParser().parse(request)
        tutorial_serializer = TutorialSerializer(data=tutorial_data)
        if tutorial_serializer.is_valid():
            return JsonResponse(, status=status.HTTP_201_CREATED) 
        return JsonResponse(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        count = Tutorial.objects.all().delete()
        return JsonResponse({'message': '{} Tutorials were deleted successfully!'.format(count[0])}, status=status.HTTP_204_NO_CONTENT)
@api_view(['GET', 'PUT', 'DELETE'])
def tutorial_detail(request, pk):
        tutorial = Tutorial.objects.get(pk=pk) 
    except Tutorial.DoesNotExist: 
        return JsonResponse({'message': 'The tutorial does not exist'}, status=status.HTTP_404_NOT_FOUND) 
    if request.method == 'GET': 
        tutorial_serializer = TutorialSerializer(tutorial) 
        return JsonResponse( 
    elif request.method == 'PUT': 
        tutorial_data = JSONParser().parse(request) 
        tutorial_serializer = TutorialSerializer(tutorial, data=tutorial_data) 
        if tutorial_serializer.is_valid(): 
            return JsonResponse( 
        return JsonResponse(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
    elif request.method == 'DELETE': 
        return JsonResponse({'message': 'Tutorial was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT)
def tutorial_list_published(request):
    tutorials = Tutorial.objects.filter(published=True)
    if request.method == 'GET': 
        tutorials_serializer = TutorialSerializer(tutorials, many=True)
        return JsonResponse(, safe=False)

Test the CRUD with APIs

Run our Django Project with command: python runserver 8080.
It starts development server at / http://localhost:8080/.

Using Postman, we’re gonna test all the Apis above.

  1. POST /tutorials Api: Create a new Tutorial

  2. django-rest-api-tutorial-example-post-method

  3. GET /tutorials Api: Retrieve all Tutorials

  4. django-rest-api-tutorial-example-get-method

  5. GET /tutorials/:id Api: Retrieve a single Tutorial by id

  6. django-rest-api-tutorial-example-get-method-one

  7. PUT /tutorials/:id Api: Update a Tutorial

  8. django-rest-api-tutorial-example-put-method

    This is all Tutorials after updating several ones:


  9. GET /tutorials?title=res: Find all Tutorials which title contains ‘res’

  10. django-rest-api-tutorial-example-get-method-with-param

  11. GET /tutorials/published Api: Find all published Tutorials

  12. django-rest-api-tutorial-example-get-method-path

  13. Delete a Tutorial using DELETE /tutorials/:id Api

  14. django-rest-api-tutorial-example-delete-method-one

  15. Delete all Tutorials using DELETE /tutorials Api

  16. django-rest-api-tutorial-example-delete-method


Today, we’ve learned how to build a Python Rest Api Server using Django Rest Framework. We also know way to create new Django app, define a Django Model, migrate it to database, write the Views and define Url patterns for handling HTTP GET/POST/PUT/DELETE requests.

You can also find ways to build more Django Projects that connect to database in following posts:
Django Rest Api with MySQL example | Django Rest Framework
Django Rest Api with MongoDB example | Django Rest Framework
Django Rest Api with PostgreSQL example | Django Rest Framework

Or run with one of these Clients:

Happy learning! See you again.

Further Reading

Fullstack CRUD App:

Source code

You can find the complete source code for this example on Github.

28 thoughts to “Django: POST, PUT, GET, DELETE requests example | Rest Apis”

  1. Thanks a lot, you save me! Really useful and very clean code. Congratulations!

  2. Wow !Really great Django tutorial. Only read it quickly so that I can go over again later! This is really helpful for me. Many many thanks for sharing such a wonderful way to write Django Rest API.

  3. doesn’t need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.

  4. I thоught this tutorial is extremely informative. I appreciate yoᥙ spending some time ɑnd energy to write this Django Rest APIs.

  5. I think the admin of this web site is actually working hard for his tutorials, because here every tutorial is quality based data.

Comments are closed to reduce spam. If you have any question, please send me an email.