Make sure you have python 3 installed on your machine. This tutorial will be covered based on Ubuntu 20 Operating System.
Visit this link if you didn't install Python yet!
- Check your Python installed successfully or not
python3 --version
- Update the packages
sudo apt update
- Install pip and Python Virtual Environment
sudo apt install python3-pip python3-venv
- Create a new directory in your machine and allow Read Write permission to it
sudo mkdir test
cd test
sudo chmod -R 777 ./ #You can edit permission later
- Create your Python Virtual Environment, here I named it my_env
python3 -m venv my_env
- Enable your virtual environment
source my_env/bin/activate
- Install Django
pip install django
- Check Django installed successfully or not
django-admin --version
- Create a new project with Django
django-admin startproject my_project .
ls # You will see a file named manage.py
- Now, Start the server!
python3 manage.py runserver
A server will run on your machine on 8000 port.
Now open your browser and copy and paste the link http://127.0.0.1:8000/ or http://localhost:8000 or localhost:8000
If you see something like the screenshot below then Congratulation! You successfully installed Python Django on your machine.
- Create an app
django-admin startapp my_rest_api_app
- Install the main framework
pip install djangorestframework
- Add 'rest_framework' to your INSTALLED_APPS setting.
INSTALLED_APPS = [
...
'rest_framework',
]
How to install MongoDB on Ubuntu
- Import the public key used by the package management system.
wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
The operation should respond with an OK
- However, if you receive an error indicating that gnupg is not installed, you can:
- Install gnupg and its required libraries using the following command:
sudo apt-get install gnupg
- Once installed, retry importing the key:
wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
- Create a list file for MongoDB
Create the list file /etc/apt/sources.list.d/mongodb-org-5.0.list for your version of Ubuntu. If you are unsure of what Ubuntu version the host is running, open a terminal or shell on the host and execute lsb_release -dc
- Ubuntu 20.04 (Focal)
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
- Ubuntu 18.04 (Bionic)
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
- Ubuntu 16.04 (Xenial)
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
- Reload local package database
sudo apt update
- Install the MongoDB packages
sudo apt-get install -y mongodb-org
To install a specific release, you must specify each component package individually along with the version number, as in the following example:
sudo apt-get install -y mongodb-org=5.0.7 mongodb-org-database=5.0.7 mongodb-org-server=5.0.7 mongodb-org-shell=5.0.7 mongodb-org-mongos=5.0.7 mongodb-org-tools=5.0.7
- Start MongoDB
sudo systemctl start mongod
#or
sudo service mongod start
- Verify that MongoDB has started successfully
sudo systemctl status mongod
#or
sudo service mongod status
You can optionally ensure that MongoDB will start following a system reboot by issuing the following command:
sudo systemctl enable mongod
- Stop MongoDB
sudo service mongod stop
- Restart MongoDB
sudo service mongod restart
- Begin using MongoDB
mongosh
#or
mongo
- To exit from MongoDB command shell
exit
#or
bye
- First add your app in installed app list
- Install djongo plugin or library
pip install djongo
- Configuring MongoDB
Navigate to the settings.py file and change the DATABASES setting as follows:
DATABASES = {
'default' : {
'ENGINE' : 'djongo',
'NAME' : 'my_custom_db' #database name
}
}
- Let’s define a model for the users in the models.py file of the my_rest_api_app app that we have created
from django.db import models
class User(models.Model):
name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
address = models.TextField(max_length=200)
def __str__(self):
return self.name
- Let’s migrate the model into the database
python3 manage.py makemigrations
python3 manage.py migrate
If you face any problem during makemigrations command then may be your pymongo version not comptible with djongo version
pip install pymongo==3.12.3
- If you see something like this then database migration completed succesfully
- Next, let’s create a serializer class. When users make requests to the API, the serializers format the corresponding responses. Create a new serializers.py file in the my_rest_api_app app folder. Make the necessary imports as demonstrated below and create the UserSerializer class.
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ( 'name', 'email', 'address')
- Next, let’s create the views that will handle the request and response actions of our API. Create the UserList view in the views.py file of the my_rest_api_app app.
from django.shortcuts import render
from rest_framework import generics
from .models import User
from .serializers import UserSerializer
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
- Create a new urls.py file inside the my_rest_api_app app directory.
Create the urlpatterns as follows inside:
from django.urls import path
from my_rest_api_app import views
urlpatterns = [
path('', views.UserList.as_view()),
]
- Next, set up the urls.py file of the my_project to point to the app level urlpatterns. Then, include a path to the urls.py file of the my_rest_api_app app.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('my_rest_api_app.urls')), # add this line
]
The endpoint receives the actions ‘LIST’ and ‘CREATE’ actions of the UserList view.
Django REST framework comes shipped with the browsable API. You can test your API endpoints with the browsable API.
- Activate the test server:
python3 manage.py runserver
- Then navigate to 127.0.0.1:8000/api/ on your browser to create users.
- Create an user
- After creating an user successfully, previous users data will show in a list.
- Direct data view from database
- Created a Python Django REST API project
- Connected our project with MongoDB
- Created sample REST API for testing purpose