Django RestApis example – GET/POST/PUT/DELETE requests to MongoDb database

django-restapi-mongodb-example-django-rest-framework-tutorial-feature-image

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

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/update/[id]: update a customer by id
  • DELETE /customers/[id]: delete a customer by id

We will config the Project to work with MongoDb database.

Project structure

There are several folders and files in our Django project:

django-restapi-mongodb-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 MongoDb 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-mongodb-example-django-rest-framework-tutorial-create-project

Install Django MongoDb connector

We have to install Django MongoDb connector to work with MongoDb database.
In this tutorial, we use djongo:
pip install djongo.

Setup MongoDb Database engine

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

Create Customers App

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

django-restapi-mongodb-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:

Add Django Rest framework & RestApi App to Django project

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

Implement Django RestApi App

Data Model
Create Data Model

customers/models.py

Run initial migration for data model

Run following Python script:
python manage.py makemigrations customers

We can see output text:

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

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:

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

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:

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

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.

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

Test results

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

– Save customer using POST HTTP method:

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

django-restapi-mongodb-example-django-rest-framework-tutorial-mongodb-table-save-result

– Get list of customers using GET HTTP method:

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

– Get a customer by id using GET HTTP method:

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

– Update a customer by id using PUT HTTP method:

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

– Delete a customer by id using DELETE HTTP method:

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

– Check MongoDb Database:

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

Source Code

Django-RestApi-MongoDb

By grokonez | February 19, 2019.



Related Posts


Got Something To Say:

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

*