DEV Community

Cover image for Build a Rest API with Python - The easiest way
Ousseynou Diop
Ousseynou Diop

Posted on

Build a Rest API with Python - The easiest way

In this tutorial we will transform our Django phonebook Application to a Rest API

A REST API defines a set of functions which developers can perform requests and receive responses via HTTP protocol such as GET, POST, PUT and DELETE

Think REST API as a web service that provide you the data you want to use in your application(mobile or front-end client).

The key component for a REST API request are:

GET — The most common option, returns some data from the API based on the given endpoint .
POST — Creates a new record and add it to the database.
PUT — Update an existing record.
DELETE — Deletes the record on the given endpoint.

Getting started

$ git clone
$ cd django-phonebook

Application setup

$ pipenv install
Creating a virtualenv for this project…
Using /usr/bin/python3.7m (3.7.5) to create virtualenv…
$ pipenv shell
Spawning environment shell (/usr/bin/zsh). Use 'exit' to leave.
. /home/username/.local/share/virtualenvs/phonebook_rest_api-9zIZds3o/bin/activate

Run the application

(my-env) $ python runserver

Notice i use pipenv instead of pip but you can use pip if you want it's up to you.

The application is running at http://localhost:800/

├── accounts
│   ├──
│   ├──
│   ├──
│   ├──
│   ├── migrations
│   │   └──
│   ├──
│   ├──
│   ├──
│   └──
├── contact
│   ├──
│   ├──
│   ├──
│   ├── migrations
│   │   ├──
│   │   └──
│   ├──
│   ├──
│   ├──
│   └──
├── db.sqlite3
├── phonebook
│   ├──
│   ├──
│   ├──
│   ├──
│   └──
├── Pipfile
├── Pipfile.lock
├── requirements.txt
└── templates
   ├── accounts
   │   ├── login.html
   │   └── register.html
   ├── base.html
   ├── contact
   │   ├── contact_details.html
   │   ├── contact_list.html
   │   ├── delete_contact.html
   │   ├── new_contact.html
   │   └── update_contact.html
   ├── index.html
   └── partials
       └── _navbar.html

This is our folder structure.

Setup Django REST Framework

Django REST framework is a powerful and flexible toolkit for building Web APIs.

(myenv) $ pipenv install djangorestframework

In phonebook/ add

# Application definition
   'rest_framework', # add this

Serialize the contact Table(Model)

Let's create a new file -- contact/

# contact/
from rest_framework import serializers
from .models import Contact

class ContactSerializer(serializers.ModelSerializer):
   class Meta:
       model = Contact
       fields = '__all__'

Preparing the data

Create a new file -- contact/

# contact/
from rest_framework import viewsets
from .serializers import ContactSerializer
from .models import Contact

class ContactViewSet(viewsets.ModelViewSet):
   serializer_class = ContactSerializer
   queryset = Contact.objects.all()

Update our contact/

from django.urls import path, include # add this
from rest_framework.routers import DefaultRouter  # add this
from .views import (
   index, contact_list,
   new_contact, contact_details,
   update_contact, delete_contact
from .api import ContactViewSet  # add this
router = DefaultRouter()  # add this
router.register(r'contacts', ContactViewSet,
               basename='contact')  # add this

urlpatterns = [
   path("api/", include(router.urls)),
   path("", index, name="home"),
   path("contacts/", contact_list, name="contacts"),
   path("contacts/new/", new_contact, name="new"),
   path("contacts/<int:id>/details/", contact_details, name="details"),
   path("contacts/<int:id>/update/", update_contact, name="update"),
   path("contacts/<int:id>/delete/", delete_contact, name="delete"),

Open your browser and go to http://localhost:8000/api/
You will see something like this :

Content-Type: application/json
Vary: Accept

   "contacts": "http://localhost:8000/api/contacts/"

Click on the link what you see ?

  • You should see a list of contact if they exist in your database.
  • You can also create new data

Let's wrap it

In this tutorial you learned how to create a REST API with Django and Django Rest Framework.
In the next tutorial i will handle the more complex topic like :

  • Authentication and authorization
  • Serialize nested object
  • Serialize relation field
  • etc..

See you in the next tutrial

Top comments (6)

gabrielviviani profile image

I'll start a project Using FastAPI. It's the best open source docs i've ever seen.
And is also a micro Framework.

xarala221 profile image
Ousseynou Diop

Try it out.
It's great!

maximoguerrero profile image
Maximo Guerrero

Nice post! I have been using flask + flask-Restplus just to keep things lightweights.

xarala221 profile image
Ousseynou Diop

Thank you Maximo.

Flask really love it.
i use it to build MicroServices and small application.


astrit profile image

I have never done something like this in python but plan to do, what would you use for documentation and authentication ?

xarala221 profile image
Ousseynou Diop

I use the knox( package for authentication and Django Rest Framework ( is well documented.

If you want to use something lightweight i suggest you to use Flask.