Django RestApis example – GET/POST/PUT/DELETE requests MySQL database with Django REST Framework

django-restapi-mysql-example-django-rest-framework-tutorial

In the tutorial, we’re gonna look at way to create Django RestAPIs with Get/Post/Put/Delete requests to interact with MySQL Database using Django REST Framework.

Related Post: Django + Angular 6 example | Django Rest Framework + MySQL CRUD example

Django RestApi example Overview

Goal

The project create a set of Rest-APIs for GET/POST/UPDATE/DELETE APIs:

  • GET /customers/: get all customers
  • GET /customers/[id]: get a customer by id
  • POST /customers/: save a customer
  • PUT /customers/[id]: update a customer by id
  • DELETE /customers/[id]: delete a customer by id

We will config the Project to work with MySQL database.

Project structure

There are several folders and files in our Django project:

django-restapi-mysql-example-django-rest-framework-tutorial-project-structure

customers/apps.py: declares CustomersConfig class (subclass of the django.apps.AppConfig) that represents our Django app and its configuration.
gkzRestApi/settings.py: configures settings for the Django project, including INSTALLED_APPS list with Django REST framework and Customers Application.
customers/models.py: defines Customer data model class (subclass of the django.db.models.Model).
migrations/0001_initial.py: is generated by makemigrations command, includes the code to create the Customer model, will be run by migrate to generate MySQL database table for Customer model.
customers/serializers.py: declares CustomerSerializer class (subclass of rest_framework.serializers.ModelSerializer) for Customer instances to manage serialization to JSON and deserialization from JSON.
customers/views.py: contains methods to process HTTP requests and produce HTTP responses (using CustomerSerializer).
customers/urls.py: defines urlpatterns to be matched with request functions in the views.py.
gkzRestApi/urls.py: defines root URL configurations that includes the URL patterns declared in customers/urls.py.

Setup Django RestApi project

Install Django REST framework

Django REST framework works on top of Django and helps us to build RESTful Web Services flexibly. To install this package, run command:
pip install djangorestframework

Create RestApi project

Create Django project named gkzRestApi with command:
django-admin startproject gkzRestApi

django-restapi-mysql-example-django-rest-framework-tutorial-create-project

Install & Import Python MySQL Client

We have to install Python MySQL Client to work with MySQL database.
In this tutorial, we use pymysql: pip install pymysql.

Once the installation is successful, import this module in gkzRestApi/__init__.py:

import pymysql

pymysql.install_as_MySQLdb()
Setup MySQL Database engine

Open gkzRestApi/settings.py and change declaration of DATABASES:

DATABASES = {
   'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'testdb',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}
Create Customers App

Run following commands to create new Django App named customers:
cd gkzRestApi
python manage.py startapp customers

django-restapi-mysql-example-django-rest-framework-tutorial-create-project-app

Open customers/apps.py, we can see CustomersConfig class (subclass of the django.apps.AppConfig) that represents our Django app and its configuration:

from django.apps import AppConfig


class CustomersConfig(AppConfig):
    name = 'customers'
Add Django Rest framework & RestApi App to Django project

Open gkzRestApi/settings.py, find INSTALLED_APPS, then add:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Django REST framework 
    'rest_framework',
    # Customers application 
    'customers.apps.CustomersConfig',
]

Implement Django RestApi App

Data Model
Create Data Model

customers/models.py

from django.db import models


class Customer(models.Model):
    name = models.CharField(max_length=70, blank=False, default='')
    age = models.IntegerField(blank=False, default=1)
    active = models.BooleanField(default=False)
Run initial migration for data model

Run following Python script:
python manage.py makemigrations customers

We can see output text:

Migrations for 'customers':
  customers\migrations\0001_initial.py
    - Create model Customer

It indicates that the customers/migrations/0001_initial.py file includes code to create Customer data model:

# Generated by Django 2.1.7 on 2019-02-17 08:10

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Customer',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(default='', max_length=70)),
                ('age', models.IntegerField(default=1)),
                ('active', models.BooleanField(default=False)),
            ],
        ),
    ]

The generated code defines a subclass of the django.db.migrations.Migration. It has an operation for creating Customer model table. Call to migrations.CreateModel() method will create a table that allows the underlying database to persist the model.

Run the following Python script to apply the generated migration:
python manage.py migrate customers

The output text:

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

Check MySQL Database, now we can see that a table for Customer model was generated and it’s named customers_customer:

django-restapi-mysql-example-django-rest-framework-tutorial-mysql-table

Create Serializer class

We need a Serializer class for Customer instances to manage serialization to JSON and deserialization from JSON.

– This CustomerSerializer will inherit from rest_framework.serializers.ModelSerializer superclass.
ModelSerializer class automatically populates a set of default fields and default validators, we only need to specify the model class.

Now, under customers package, create serializers.py file:

from rest_framework import serializers 
from customers.models import Customer


class CustomerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Customer
        fields = ('id',
                  'name',
                  'age',
                  'active')

Meta inner class declares 2 attributes:
model: specifies the model related to the serializer
fields: specifies a tuple of field names that we want to include in the serialization

Create API Views

Open customers/views.py file and declare two functions:
customer_list(): get list of customers, save a new customer
customer_detail(): get/update/delete customer by id

from django.shortcuts import render 
from django.http import HttpResponse
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser 
from rest_framework import status

from customers.models import Customer
from customers.serializers import CustomerSerializer

@csrf_exempt
def customer_list(request):
    if request.method == 'GET':
        customers = Customer.objects.all()
        customers_serializer = CustomerSerializer(customers, many=True)
        return JsonResponse(customers_serializer.data, safe=False)
        # In order to serialize objects, we must set 'safe=False'

    elif request.method == 'POST':
        customer_data = JSONParser().parse(request)
        customer_serializer = CustomerSerializer(data=customer_data)
        if customer_serializer.is_valid():
            customer_serializer.save() 
            return JsonResponse(customer_serializer.data, status=status.HTTP_201_CREATED) 
        return JsonResponse(customer_serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@csrf_exempt 
def customer_detail(request, pk):
    try: 
        customer = Customer.objects.get(pk=pk) 
    except Customer.DoesNotExist: 
        return HttpResponse(status=status.HTTP_404_NOT_FOUND) 
 
    if request.method == 'GET': 
        customer_serializer = CustomerSerializer(customer) 
        return JsonResponse(customer_serializer.data) 
 
    elif request.method == 'PUT': 
        customer_data = JSONParser().parse(request) 
        customer_serializer = CustomerSerializer(customer, data=customer_data) 
        if customer_serializer.is_valid(): 
            customer_serializer.save() 
            return JsonResponse(customer_serializer.data) 
        return JsonResponse(customer_serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
 
    elif request.method == 'DELETE': 
        customer.delete() 
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)
Route Urls to Views functions

Create urls.py in customers folder, now we will define urlpatterns to be matched with request functions in the views.py.

from django.conf.urls import url 
from customers import views 
 
urlpatterns = [ 
    url(r'^customers/$', views.customer_list),
    url(r'^customers/(?P[0-9]+)$', views.customer_detail),
]

Now we must include above URL patterns in root URL configurations.
Open gkzRestApi/urls.py, replace the code:

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

Test results

To start the RestApi server, run command:
python manage.py runserver

– Save customer using POST HTTP method:

django-restapi-mysql-example-django-rest-framework-tutorial-post-method

– Get list of customers using GET HTTP method:

django-restapi-mysql-example-django-rest-framework-tutorial-get-all-method

– Get a customer by id using GET HTTP method:

django-restapi-mysql-example-django-rest-framework-tutorial-get-method

– Update a customer by id using PUT HTTP method:

django-restapi-mysql-example-django-rest-framework-tutorial-put-method

– Delete a customer by id using DELETE HTTP method:

django-restapi-mysql-example-django-rest-framework-tutorial-delete-method

– Check MySQL Database:

django-restapi-mysql-example-django-rest-framework-tutorial-mysql-table-result

Source Code

Django-RestApi-MySQL

25 thoughts on “Django RestApis example – GET/POST/PUT/DELETE requests MySQL database with Django REST Framework”

  1. Usually I don’t read post on blogs, but I wish to say that this write-up very forced me to take
    a look at and do it! Your writing taste has
    been surprised me. Thank you, quite great post.

  2. I loved as much as you’ll receive carried out right here.

    The sketch is attractive, your authored material stylish.
    nonetheless, you command get got an edginess over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield
    this increase.

  3. Howdy would you mind sharing which blog platform you’re working
    with? I’m planning to start my own blog soon but I’m having a hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design seems different then most blogs and
    I’m looking for something unique. P.S My apologies for
    getting off-topic but I had to ask!

  4. I аbsolutely love your blog.. Pleasant colors & theme. Did you build this site yourself?
    Please reply baaсk as I’m hoping to create my own site and want to learn where you got thіs from or exacgly what the thyеme iis called.
    Kudos!

  5. With havin so much written content do you ever run into any problems
    of plagorism or copyright violation? My site has a lot of completely unique content I’ve either written myself or outsourced but it looks like a lot of it is
    popping it up all over the internet without my authorization.
    Do you know any ways to help stop content from being stolen?
    I’d really appreciate it.

  6. When I originally left a comment I appear to have clicked the -Notify
    me when new comments are added- checkbox and now whenever a comment is added I get 4 emails with the same comment.
    Is there a way you are able to remove me from that service?
    Thank you!

  7. Hi would you mind sharing which blog platform you’re working with?
    I’m looking to start my own blog soon but I’m having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most
    blogs and I’m looking for something unique.
    P.S Sorry for being off-topic but I had to ask!

  8. Hi there just wanted to give you a quick heads up. The text in your content seem to
    be running off the screen in Internet explorer.
    I’m not sure if this is a formatting issue or something to
    do with browser compatibility but I thought I’d post to let you
    know. The style and design look great though!
    Hope you get the issue solved soon. Kudos

  9. Its like you read my thoughts! Үou appear to know so much about this, like
    you ᴡrote the e-book in it or something. I think thɑt уou just can do
    with а few percent to pressure the messaɡe house a bit,
    howеver other than thɑt, tһis is excellent blog.
    A gгeat read. I’lⅼ definitely be back.

  10. Good day! This is my 1st comment here so I just wanted to give a
    quick shout out and say I truly enjoy reading through your blog posts.
    Can you suggest any other blogs/websites/forums
    that cover the same topics? Thank you!

  11. What i do not understood is in reality how
    you’re now not actually a lot more neatly-favored than you might be now.
    You are so intelligent. You already know thus considerably when it comes to this matter, made
    me personally believe it from so many varied angles. Its like women and
    men aren’t fascinated except it’s one thing to accomplish
    with Lady gaga! Your own stuffs excellent. Always deal with it
    up!

  12. you’re really a just right webmaster. The website loading speed is amazing.
    It seems that you’re doing any unique trick.
    Also, The contents are masterpiece. you have done a wonderful process on this topic!

  13. I absolutely love your website.. Great colors & theme.
    Did you develop this site yourself? Please reply back as I’m trying to create
    my own site and would love to know where you got this from or exactly
    what the theme is called. Thanks!

  14. Oh my goodness! Awesome article dude! Thank you, However I am having problems with
    your RSS. I don’t understand why I am unable to join it.

    Is there anybody else getting similar RSS issues? Anybody who knows the answer will you kindly respond?
    Thanks!!

  15. Thanks for the tips you are revealing on this website. Another thing I’d like to say is that getting hold of copies of your credit file in order to scrutinize accuracy of each detail may be the first action you have to undertake in credit restoration. You are looking to clean up your credit file from destructive details errors that mess up your credit score.

Leave a Reply

Your email address will not be published. Required fields are marked *