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 https://github.com/xarala221/django-phonebook.git
$ 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 manage.py 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
β βββ admin.py
β βββ apps.py
β βββ forms.py
β βββ __init__.py
β βββ migrations
β β βββ __init__.py
β βββ models.py
β βββ tests.py
β βββ urls.py
β βββ views.py
βββ contact
β βββ admin.py
β βββ apps.py
β βββ __init__.py
β βββ migrations
β β βββ 0001_initial.py
β β βββ __init__.py
β βββ models.py
β βββ tests.py
β βββ urls.py
β βββ views.py
βββ db.sqlite3
βββ manage.py
βββ phonebook
β βββ asgi.py
β βββ __init__.py
β βββ settings.py
β βββ urls.py
β βββ wsgi.py
βββ Pipfile
βββ Pipfile.lock
βββ README.md
βββ 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/settings.py add
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # add this
'contact',
]
Serialize the contact Table(Model)
Let's create a new file -- contact/serializers.py
# contact/serializers.py
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/api.py
# contact/api.py
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/urls.py
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 :
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
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)
I'll start a project Using FastAPI. It's the best open source docs i've ever seen.
And is also a micro Framework.
Try it out.
It's great!
Nice post! I have been using flask + flask-Restplus just to keep things lightweights.
Thank you Maximo.
Flask really love it.
i use it to build MicroServices and small application.
Regards
I have never done something like this in python but plan to do, what would you use for documentation and authentication ?
I use the knox(james1345.github.io/django-rest-kn...) package for authentication and Django Rest Framework (django-rest-framework.org/ is well documented.
If you want to use something lightweight i suggest you to use Flask.
Regards