How to Set Up a REST Service or a Web Application in Django

How to Set Up a REST Service or a Web Application in Django

A tutorial for beginners on how to get started using Python and Django, and then develop a simple REST service using them...

A tutorial for beginners on how to get started using Python and Django, and then develop a simple REST service using them...

Introduction to Django and REST

Django is a very versatile framework, primarily used for developing web applications, but it is also widely used in creating mobile app backends and REST APIs, among other things. Here we will take a quick look at how to make these things possible using Django.

As you all probably know, REST stands for “Representational State Transfer.” Basically, what happens is that a user (or some software agent on one end) provides some input (or performs some activity) and the result of those inputs (or activities) are sent to the server side using a protocol that allows a request to be sent to the server (in most cases a HTTP protocol is used, but it doesn't need to be HTTP, as long as it can support a request/response scheme). The server, on receiving the request, makes appropriate changes to the state of the system (hence we call it “State Transfer”).

A Brief Discussion on How to Create a Django Project

Django runs on HTTP protocol, and hence it is very handy in creating a REST API or a RESTful application. It allows the user to provide inputs on a web interface (or any interface that is capable of sending a HTTP request object to the Django application). In our examples in this document, we will be considering web application interfaces, but you can easily stretch them to a mobile app or any other app that can send a similar HTTP request.

In order to understand how to do these things, we need to know a bit of Django here. This is my first post in a series of 5 posts on the same topic, so, in this document, I will acquaint you with certain Django files that are of the utmost importance, along with the basic structure of a Django app (please note that 'Django' is pronounced as 'jango', NOT D-jango. The first character, 'D,' is silent.).

A 'Django project' is composed of a number of 'Django applications' that are stitched together with some logic. The first thing that you do when creating a Django project is to install Django in your Python library. This is usually done by running the command pip install Django==. You may skip the version number part, in which case the latest version of Django that can be handled by your OS and your Python distro installed on your system will be installed. Fair enough.

Once the installation is successfully complete, you will find a file named “django-admin” in the path of your computer. (run which django-admin to see where it exists; on my system it is in /usr/bin/django-admin). To create a project, you need to execute the following command in a directory of your choice. Preferably create a new directory, cd into it and run the following command:

#> django-admin  startproject 

Your project name has be to provided to create the Django project. For example, let us assume I am creating a project named “testyard.” In order to create my project, I need to execute the following command:

#> django-admin startproject testyard

The above command creates the following directory structure in the directory where you executed the above mentioned command.

testyard/
    manage.py
    testyard/
        __init__.py
        settings.py
        urls.py
        wsgi.py

A Discussion on the Files Created Above

The first file, manage.py, is very important. This is the file that will eventually assist you in creating applications, running the Django test web server, running Django management tasks (not covered in this document, but we will take look at it in a later article), and a host of other activities. The __init__.py file in the next level ensures that we will be working in an object-oriented environment. Next comes the two most important files: settings.py and urls.py. We will discuss the settings.py file first and urls.py next.

  • settings.py: This file contains the settings for the Django applications to work. Some of the more important config params in this file are the database connection parameters (username, password, database name, DB host, port, Engine, etc.), static file locations, Template Loaders, Middleware classes (we will be dicussing this in another article, but just keep in mind that these are the programs that interact with the request object before they reach the “view” functions, so they are capable of changing the request before it can be processed), installed apps, root urlconf (we will discuss this in this article later), etc. You are also free to write your own application specific settings file in the same location. However, you need to give it a different name and then import settings.py into it. There are a load of other parameters in settings.py and I would request you to go through the settings.py GitHub repo and figure out the parameters.
  • urls.py: This file contains the map of the path requested by a client (browser or a bot) to the specific view function that needs to be called when the given path is requested by an HTTP request. You will find a sample of such a urls.py file in this GitHub repo. This file is also known as the urlconf.

The file named wsgi.py exists to allow the applications you are creating to run on uWSGI and Nginx (the production environment stuff). We will be taking a look at this file later in this article.

Once these files have been created, you can start creating applications inside the project. But first, you need to figure out if the previous procedure is working fine with a server. So for that purpose, you need to run the application's development server.

To do this, you need to run the following command on the command prompt. Note that in order to run this, you need to be in the same directory where “manage.py” exists.

#>python manage.py runserver 0.0.0.0:8080

This command will start the development server. Now, you should be able to go to a browser, type in localhost:8080/login/, and you should be able to see the login screen if urls.py has an entry for that URL path. Alternatively, you may just type localhost:8080/ to see if your Django server is running.

So that makes you capable enough to start creating a REST API using Python/Django. In the subsequent sections we will demonstrate how to write code to create the REST API.

View Files in Django

The views.py file in Django follows a variation of the the MVC design pattern, and it is normally referred to as the MVT pattern. The 'M' stands for the model (the DB schema), V stands for views.py, which in an MVC framework is the controller part, while the 'T' stands for templates, which in an MVC framework would be the view component.

Since we will be looking at the REST API first, we will concentrate on the views.py file. First, have a look at the handlers.py file at the following GitHub repo. In this program, the code that is to be in views.py has been put into handlers.py, but for all intents and purposes, they work in the same manner. You may consider the code in handlers.py to be that of views.py in this example (actually, this was some code I wrote long back when I was just starting to dabbling in Django; hence I made something to see if Django is flexible enough, and found that it sure was flexible).

The Structure and Behavior of Django

The views.py file will contain one or more functions (note that it may also contain classes, and we will take a look at classes in views.py in another post), and the functions will contain only one argument: a “request.” The “request” is basically an instance of the HttpRequest class (defined by Django). All view functions in a Django app consume an instance of this HttpRequest class and return an instance of the HttpResponse class.

Why do we need to have multiple functions in the views.py file? This is because you might want to serve multiple pages or responses, each of which has a different URL path. For example, you might want to serve a login page, a registration page, an activity to check the login credentials of the user who is trying to login into your app, and a dashboard page. Each of these pages will have a different URL path, say, http://mywebsite.com/login for login page, http://mywebsite.com/registration** **for registration page, and so on. So each of these URLs will need a separate function to handle the request. Hence, we need one function for each of these actions in the views.py file.

How do we associate each of the activities mentioned above with a specific views.py function? This is where the urls.py file comes into play. urls.py has a map of each URL path to a specific function in views.py of a particular Django app (remember we mentioned in the begining that a Django project is composed of one or more Django apps. We will get to the apps part in a moment). A urls.py looks something like the following:

urlpatterns = patterns('',
(r'^time/
, current_datetime),
(r'^savewhatyoulookedat/login/
, userLogin),
(r'^savewhatyoulookedat/register/
, userRegister),
(r'^savewhatyoulookedat/
, saveURL),
(r'^savewhatyoulookedat/logout/
, userLogout),
(r'^savewhatyoulookedat/downloadPlugin/
, firefoxPluginDownload),
(r'^savewhatyoulookedat/managedata/
, manageData),
(r'^savewhatyoulookedat/commandHandler/
, executeCommand),
(r'^savewhatyoulookedat/showimage/
, showImage),
(r'^savewhatyoulookedat/search/
, searchURL),
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the another line to enable the authority:
# (r'^admin/', include(admin.site.urls)),
)

Basically, as you can see, the mapping is actually between a regular expression that should match the URL path and a function in the views.py file. As you create more activity handlers in your views.pyfile, you keep adding an entry for each of them in the urls.py file. For a Django project with multiple applications, the urls.py file might also look like the following:

urlpatterns += patterns('',
url(r'^%s
%mysettings.REGISTER_URL, 'skillstest.Auth.views.register', name='newuser'),
url(r'^%s
%mysettings.DASHBOARD_URL, 'skillstest.views.dashboard', name='dashboard'),
url("%s$"%mysettings.LOGIN_URL, 'skillstest.Auth.views.login', name='login'),
url(r'%s
%mysettings.MANAGE_TEST_URL, 'skillstest.Tests.views.manage', name='managetests'),
url(r'%s
%mysettings.CREATE_TEST_URL, 'skillstest.Tests.views.create', name='createtests'),
url(r'%s
%mysettings.EDIT_TEST_URL, 'skillstest.Tests.views.edit', name='edittests'),
url(r'%s
%mysettings.ABOUTUS_URL, 'skillstest.views.aboutus', name='aboutus'),
url(r'%s
%mysettings.HELP_URL, 'skillstest.views.helpndocs', name='helpndocs'), url(r'%s%mysettings.CAREER_URL, 'skillstest.views.careers', name='careers'),
... ... ...

'Auth' and 'Tests' are the names of the applications in the “skillstest” project. Don't worry about the variables in uppercases — they are defined elsewhere and are of no consequence to our example here.

So, now let us see how to create an application inside a project. We do that by executing the following command:

**python manage.py startapp **

For example, if our app name is “Letsplay”, then we would run

python manage.py startapp Letsplay

The above command creates a directory structure like the following:

Letsplay/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py

In the above structure, we will focus mostly on the views.py and the models.py files. However, we will also touch upon the others first.

The admin.py file is required if you want to customize your admin panel in Django. Normally, if you try to access the URL http://localhost:8080/admin, you would see an admin panel. This will display you all the models you have (we will discuss models in just a bit), the config settings of your django project (in read only mode, of course), etc.

The apps.py file allows the creator of the Django app to put in some application specific parameters. Each app in a Django project has its own apps.py file.

The tests.py file allows the app creator to write tests for the app. This file needs to conform to a certain structure. It needs to define a class for a specific test case. This class needs to have a method named setUp, and then it should have the tests defined as methods in the class itself. Unless you are a Django purist, you won't use this file to define your tests. Normally, in the real life scenarios, we have an application created using Django, another component created using some other technology, and several other components fitted together to work as a service. In such cases, we need to write tests to check the functionality of the entire scheme of things rather than just the Django part. Hence, it is almost customary to create tests as a different suite using Python or some other language like Perl or Ruby (or whatever the tester prefers).

By and large, any application you write (in Python using Django or any other language and framework), you eventually end up interacting with a database somewhere down the line. All Django apps also tend to do the same. This is where the models.py file steps in. The models.py file basically provides you with an ORM (Object-Relational-Mapping) scheme in the Django app. Hence for every table in your prefered database, you have a class defined for it in the models.py file. It looks something like this:

from django.db import models
import os, sys, re, time, datetime
import inspect
"""
'Topic' is basically category or domain.
"""
class Topic(models.Model):
	topicname = models.CharField(max_length=150)
	user = models.ForeignKey(User, null=False)
	createdate = models.DateField(auto_now=True)
	isactive = models.BooleanField(default=True)
class Meta:
verbose_name = "Topics Table"
db_table = 'Tests_topic'
def __unicode__(self):
return "%s"%(self.topicname)
class Subtopic(models.Model):
	subtopicname = models.CharField(max_length=150)
	subtopicshortname = models.CharField(max_length=50)
	topic = models.ForeignKey(Topic, blank=False, null=False)
	createdate = models.DateField(auto_now=True)
	isactive = models.BooleanField(default=True)
class Meta:
	verbose_name = "Subtopics Table"
	db_table = 'Tests_subtopic' # Name of the table in the database
def __unicode__(self):
return "%s (child of %s)"%(self.subtopicname, self.topic.topicname)
class Session(models.Model):
	sessioncode = models.CharField(max_length=50, unique=True)
	status = models.BooleanField(default=True) # Will be 'True' as soon as the user logs in, and will be 'False' when user logs out.
# The 'status' will automatically be set to 'False' after a predefined period. So users will need to login again after that period.
# The predefined value will be set in the settings file skills_settings.py. (skills_settings.SESSION_EXPIRY_LIMIT)
	user = models.ForeignKey(User, null=False, blank=False, db_column='userid_id')
	starttime = models.DateTimeField(auto_now_add=True) # Should be automatically set when the object is created.
	endtime = models.DateTimeField(default=None)
	sourceip = models.GenericIPAddressField(protocol='both', help_text="IP of the client's/user's host")
	istest = models.BooleanField(default=False) # Set it to True during testing the app.
	useragent = models.CharField(max_length=255, default="", help_text="Signature of the browser of the client/user") # Signature of the user-agent to guess the device used by the user.
# This info may later be used for analytics.
class Meta:
	verbose_name = "Session Information Table"
	db_table = 'Auth_session'
def __unicode__(self):
return self.sessioncode
def isauthenticated(self):
if self.status and self.user.active:
return self.user
else:
return None
def save(self, **kwargs):
super(Session, self).save(kwargs)

The attributes in the classes are the fields in the respective tables in the database. The name of the DB table is defined in the “class Meta” of each of the Topic and Subtopic classes with the attribute named db_table. The database associated with these tables is defined in the settings.py file (remember when we discussed settings.py file attributes?). For the datatypes used in the models.py file, you need to look up the Django documentation as there are quite a few data types and relationships and they cannot be dealt with here. In fact, the documentation for them is quite substantial. However, we have used only a few of them above and they are quite self-explanatory.

Actually, Django is quite popular because of two reasons.

  1. It provides the developer with all the boiler plate code, so the coder doesn't need to write all the boring stuff.
  2. It provides the coder with the ORM, so retrieving or setting a value in a certain row of a specific table in the DB is quite easy. That is the up side of it. There is a down side too. When you use ORM, you do not use SQL statements, and hence if the operation is a little complex, the ORM can become quite inefficient. With SQL statements, you can do some optimization to make the statement run faster, but with ORM, there is no such possiblity. For this reason, Django offers a way out. You can create “raw” SQL statements to query your DB, but this is rarely used by most developers. You should use “raw” SQL statements only when you see that the ORM way of manipulating the DB is distinctively inefficient.

Anyway, let us now move on to the final stages of this document. This happens to be the most important stage in the creation of a REST application. We will now take a look at the views.py file. Please refer to the example code below:

#User login handler
def login(request):
    if request.method == "GET":
    msg = None
if request.META.has_key('QUERY_STRING'):
    msg = request.META.get('QUERY_STRING', '')
if msg is not None and msg != '':
    msg_color = 'FF0000'
msg = skillutils.formatmessage(msg, msg_color)
else :
    msg = ""
#Display login form
curdate = datetime.datetime.now()
tmpl = get_template("authentication/login.html")
c = {
    'curdate': curdate,
    'msg': msg,
    'register_url': skillutils.gethosturl(request) + "/" + mysettings.REGISTER_URL
}
c.update(csrf(request))
cxt = Context(c)
loginhtml = tmpl.render(cxt)
for htmlkey in mysettings.HTML_ENTITIES_CHAR_MAP.keys():
    loginhtml = loginhtml.replace(htmlkey, mysettings.HTML_ENTITIES_CHAR_MAP[htmlkey])
return HttpResponse(loginhtml)
elif request.method == "POST":
    username = request.POST.get('username') or ""
password = request.POST.get('password') or ""
keeploggedin = request.POST.get('keepmeloggedin') or 0
csrfmiddlewaretoken = request.POST.get('csrfmiddlewaretoken', "")
userobj = authenticate(username, password)
if not userobj: #Incorrect password - return user to login screen with an appropriate message.
message = error_msg('1002')
return HttpResponseRedirect(skillutils.gethosturl(request) + "/" + mysettings.LOGIN_URL + "?msg=" + message)
else : #user will be logged in after checking the 'active'
field
if userobj.active:
    sessobj = Session()
clientip = request.META['REMOTE_ADDR']
timestamp = int(time.time()) 
# timestamp will be a 10 digit string.
sesscode = generatesessionid(username, csrfmiddlewaretoken, clientip, timestamp.__str__())
sessobj.sessioncode = sesscode
sessobj.user = userobj
# sessobj.starttime should get populated on its own when we save this session object.
sessobj.endtime = None
sessobj.sourceip = clientip
if userobj.istest: #This session is being performed by a test user, so this must be a test session.
sessobj.istest = True
elif mysettings.TEST_RUN: #This is a test run as mysettings.TEST_RUN is set to True
sessobj.istest = True
else :
    sessobj.istest = False
sessobj.useragent = request.META['HTTP_USER_AGENT']
# Now save the session...
sessobj.save()
#...and redirect to landing page(which happens to be the profile page).
response = HttpResponseRedirect(skillutils.gethosturl(request) + "/" + mysettings.LOGIN_REDIRECT_URL)
response.set_cookie('sessioncode', sesscode)
response.set_cookie('usertype', userobj.usertype)
return response
else :
    message = error_msg('1003')
return HttpResponseRedirect(skillutils.gethosturl(request) + "/" + mysettings.LOGIN_URL + "?msg=" + message)
else :
    message = error_msg('1001')
return HttpResponseRedirect(skillutils.gethosturl(request) + "/" + mysettings.LOGIN_URL + "?msg=" + message)
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
#User registration handler
def register(request):
    privs = Privilege.objects.all()
privileges = {}
for p in privs:
    privileges[p.privname] = p.privdesc
if request.method == "GET": #display the registration form
msg = ''
if request.META.has_key('QUERY_STRING'):
    msg = request.META.get('QUERY_STRING', '')
if msg is not None and msg != '':
    var, msg = msg.split("=")
for hexkey in mysettings.HEXCODE_CHAR_MAP.keys():
    msg = msg.replace(hexkey, mysettings.HEXCODE_CHAR_MAP[hexkey])
msg = "
%s
" % msg
else :
    msg = ""
curdate = datetime.datetime.now()
    (username, password, password2, email, firstname, middlename, lastname, mobilenum) = ("", "", "", "", "", "", "", "")
tmpl = get_template("authentication/newuser.html")# c = {
    'curdate': curdate,
    'msg': msg,
    'login_url': skillutils.gethosturl(request) + "/" + mysettings.LOGIN_URL,
    'register_url': skillutils.gethosturl(request) + "/" + mysettings.REGISTER_URL,
    'privileges': privileges,
    'min_passwd_strength': mysettings.MIN_ALLOWABLE_PASSWD_STRENGTH,
}
c = {
    'curdate': curdate,
    'msg': msg,
    'login_url': skillutils.gethosturl(request) + "/" + mysettings.LOGIN_URL,
    'hosturl': skillutils.gethosturl(request),
    \
    'register_url': skillutils.gethosturl(request) + "/" + mysettings.REGISTER_URL,
    \
    'min_passwd_strength': mysettings.MIN_ALLOWABLE_PASSWD_STRENGTH,
    'username': username,
    'password': password,
    'password2': password2,
    \
    'email': email,
    'firstname': firstname,
    'middlename': middlename,
    'lastname': lastname,
    'mobilenum': mobilenum,
    \
    'availabilityURL': mysettings.availabilityURL,
    'hosturl': skillutils.gethosturl(request),
    'profpicheight': mysettings.PROFILE_PHOTO_HEIGHT,
    'profpicwidth': mysettings.PROFILE_PHOTO_WIDTH
}
c.update(csrf(request))
cxt = Context(c)
registerhtml = tmpl.render(cxt)
for htmlkey in mysettings.HTML_ENTITIES_CHAR_MAP.keys():
    registerhtml = registerhtml.replace(htmlkey, mysettings.HTML_ENTITIES_CHAR_MAP[htmlkey])
return HttpResponse(registerhtml)
elif request.method == "POST": #Process registration form data
username = request.POST['username']
password = request.POST['password']
password2 = request.POST['password2']
email = request.POST['email']
firstname = request.POST['firstname']
middlename = request.POST['middlename']
lastname = request.POST['lastname']
sex = request.POST['sex']
usertype = request.POST['usertype']
mobilenum = request.POST['mobilenum']
profpic = ""
# userprivilege = request.POST['userprivilege']
csrftoken = request.POST['csrfmiddlewaretoken']
message = ""
# Validate the collected data...
if password != password2:
    message = error_msg('1011')
elif mysettings.MULTIPLE_WS_PATTERN.search(username):
    message = error_msg('1012')
elif not mysettings.EMAIL_PATTERN.search(email):
    message = error_msg('1013')
elif mobilenum != ""
and not mysettings.PHONENUM_PATTERN.search(mobilenum):
    message = error_msg('1014')
elif sex not in ('m', 'f', 'u'):
    message = error_msg('1015')
elif usertype not in ('CORP', 'CONS', 'ACAD', 'CERT'):
    message = error_msg('1016')
elif not mysettings.REALNAME_PATTERN.search(firstname) or not mysettings.REALNAME_PATTERN.search(lastname) or not mysettings.REALNAME_PATTERN.search(middlename):
    message = error_msg('1017')
    ....
    ....
return HttpResponse(html)

The above code has two functions, and we will discuss them shortly. But before that, please take a look at the corresponding urls.py file for these two above functions:

urlpatterns = patterns('',
	(r'^savewhatyoulookedat/login/
, login),
	(r'^savewhatyoulookedat/register/
, register)
)

As you can see above, the login function will be called when you try to access the following URL from your browser (or any other web client): http://localhost:8080/savewhatyoulookedat/login/

The 'register' function will be called when you try to access the following URL: http://localhost:8080/savewhatyoulookedat/register/

Note how the request object has been used along with some other objects that are the product of Django's ORM. For example, in the login function, there is an instance of the Session model. The DB table behind the Session model is named Auth_session and it is specified in the models.py file above. Thus, whenever a user hits one of the URLs mentioned above, the view runs some DB queries and figures out what response to send to the client. This is how a RESTful application should work, and as you can see, Django really makes it easy to develop one.

Conclusion

Django is a very extensive framework, and since we were discussing REST applications, I deliberately left out Django templates. I will be explaining templates in another post, but since REST apps do not always need an HTML interface, I am skipping it for now. Also, we have just touched on some of the concepts of Django, and there is not enough room to discuss all of them in detail here. I would suggest that you go through this post, try and understand as best as you can, and then take a look at the official Django documentation for more details on the topic.

Python Django Tutorial | Django Course

Python Django Tutorial | Django Course

🔥Intellipaat Django course: https://intellipaat.com/python-django-training/ 👉This Python Django tutorial will help you learn what is django web development &...

This Python Django tutorial will help you learn what is django web development & application, what is django and introduction to django framework, how to install django and start programming, how to create a django project and how to build django app. There is a short django project as well to master this python django framework.

Why should you watch this Django tutorial?

You can learn Django much faster than any other programming language and this Django tutorial helps you do just that. Our Django tutorial has been created with extensive inputs from the industry so that you can learn Django and apply it for real world scenarios.

Developing Restful APIs with Python, Django and Django Rest Framework

Developing Restful APIs with Python, Django and Django Rest Framework

This article is a definitive guide for starters who want to develop projects with RESTful APIs using Python, Django and Django Rest Framework.

This article is a definitive guide for starters who want to develop projects with RESTful APIs using Python, Django and Django Rest Framework.

Introduction
  • Django is a web framework written in Python
  • Python is an interpreted high-level programming language for general-purpose programming
  • API or Application Programming Interface is a set of rules and mechanisms by which one application or component interacts with the others
  • REST or Representational State Transfer is a software architecture

REST APIs

As described in a dissertion by Roy Fielding,

REST is an "architectural style' that basically exploits the existing technology and protocols of the web.
In simple definition, it is the data representation for a client in the format that is suitable for it.

Hence, RESTful + API is a commonly used terminology for the implementation of such architecture and constraints (eg. in web services).

Here is an example GET request from GitHub's API

$ curl https://api.github.com/users/joshuadeguzman

You will see an output similar to this

{
  "login": "joshuadeguzman",
  "id": 20706361,
  "node_id": "MDQ6VXNlcjIwNzA2MzYx",
  "avatar_url": "https://avatars1.githubusercontent.com/u/20706361?v=4",
  "gravatar_id": "",
  "url": "https://api.github.com/users/joshuadeguzman",
  "html_url": "https://github.com/joshuadeguzman",
  "followers_url": "https://api.github.com/users/joshuadeguzman/followers",
  "following_url": "https://api.github.com/users/joshuadeguzman/following{/other_user}",
  "gists_url": "https://api.github.com/users/joshuadeguzman/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/joshuadeguzman/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/joshuadeguzman/subscriptions",
  "organizations_url": "https://api.github.com/users/joshuadeguzman/orgs",
  "repos_url": "https://api.github.com/users/joshuadeguzman/repos",
  "events_url": "https://api.github.com/users/joshuadeguzman/events{/privacy}",
  "received_events_url": "https://api.github.com/users/joshuadeguzman/received_events",
  "type": "User",
  "site_admin": false,
  "name": "Joshua de Guzman",
  "company": "@freelancer",
  "blog": "https://joshuadeguzman.me",
  "location": "Manila, PH",
  "email": null,
  "hireable": true,
  "bio": "Android Engineer at @freelancer. Building tools for humans.",
  "public_repos": 75,
  "public_gists": 2,
  "followers": 38,
  "following": 10,
  "created_at": "2016-07-28T15:19:54Z",
  "updated_at": "2019-06-16T10:26:39Z"
}

Shown above is a data set in JSON format.

JSON or JavaScript Object Notation is an open-standard file format that uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types.
Other formats include XML, INI, CSV, etc. But today, JSON is widely use for its structure is intuitive, making it comfortable to read and map domain objects no matter what programming language is being used.

Python and Django

Python, according to its creator, Guido van Rossum, is a

high-level programming language, and its core design philosophy is all about code readability and a syntax which allows programmers to express concepts in a few lines of code.
Python uses english like words representation (eg. for methods, reserve keywords and control flow) that makes it easier for any beginner to jump right into it. It also features dynamic type system meaning it verifies the type safety of program at runtime. It also does automatic memory management.

print(5 + 5) # This will result to 10

Django is a high-level Python Web Framework that enables developers to deliver projects on time with clean and pragmatic design.

Its flagship features include a design for fast development, a secure and scalable product.

Quick Django Overview

Django's way of propagating changes to your database schema is by means of its migration modules.

Sample User model

from django.db import models

class User(models.Model):
    first_name = models.CharField(max_length=50)
    middle_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

If any changes are made on your models, run makemigrations

$ python manage.py makemigrations

Finally, you can synchronize the database with the set of models and migrations

$ python manage.py migrate

REST APIs with Django Rest Framework

DRF or Django REST Framework is a powerful and flexible toolkit for building Web APIs. It helps the developers to not reinvent the wheel by rolling out complex and solid REST API from scratch by themselves. Because when your projects become more and more complex, you will soon realise the need of using DRF or other helpful rest framework.

1. Installation & Project Setup

Create project directory

$ mkdir djangoapi

Install virtualenv via pip

A virtual environment enables a project to have additional libraries or changes in packages within its environment without disturbing global or libraries of other environments.

pip is a package management system used to install and manage software packages written in Python.

$ pip install virtualenv

To create an environment folder in your project's directory

$ cd djangoapi
$ virtualenv venv

To activate the environment

$ source venv/bin/activate

To undo these changes to your path, simply run deactivate. More on virtualenv.

Install django, djangorestframework

$ pip install django
$ pip install djangorestframework

Creating a django project

$ django-admin startproject blog

Running your project

$ python manage.py runserver

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

August 16, 2018 - 09:58:36
Django version 2.1, using settings 'blog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

The unapplied migrations refer to the default migration files included when you start a django project.

To synchronize these migration files, simply run migrate

$ python manage.py migrate

Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

The default database in our project is currently set to SQLite named db.sqlite3.

Creating a django project's app

$ cd blog
$ python manage.py startapp posts

The project structure should look like

$ find .
./posts
./posts/migrations
./posts/migrations/__init__.py
./posts/models.py
./posts/__init__.py
./posts/apps.py
./posts/admin.py
./posts/tests.py
./posts/views.py
./db.sqlite3
./blog
./blog/__init__.py
./blog/__pycache__
./blog/__pycache__/settings.cpython-36.pyc
./blog/__pycache__/wsgi.cpython-36.pyc
./blog/__pycache__/__init__.cpython-36.pyc
./blog/__pycache__/urls.cpython-36.pyc
./blog/settings.py
./blog/urls.py
./blog/wsgi.py
./manage.py

2. Model

Each model instance is a definitive source of the information about your data. In general, each model pertains to a single table in your database.

# djangoapi/blog/posts/models.py
from django.db import models

# Create your models here.

class Post(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    is_featured = models.BooleanField(default=False)

    def __str__(self):
        return self.name

__str__ is called by the str() built-in function and by the print statement to compute the "informal" string representation of an object.
If you try running makemigrations, django won't see those changes yet.

$ No changes detected

To solve this, add your posts app to your project's installed apps.

# djangoapi/blog/blog/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'posts' # Add it here
]

To continue with the migration of models

$ python manage.py makemigrations

Migrations for 'posts':
  posts/migrations/0001_initial.py
    - Create model Post

$ python manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, posts, sessions
Running migrations:
  Applying posts.0001_initial... OK


3. Serialization

Serializers allow data structure or object state to be translated into a format that can be stored or transmitted and be reconstructed later on.

Create API's serializers.py and views.py files and isolate them like this

# posts/api
posts/api/serializers.py
posts/api/views.py

# posts/migrations
posts/migrations/

# posts
posts/admin.py
posts/apps.py
posts/models.py
posts/tests.py
posts/views.py
# posts/api/serializers.py

from ..models import Post
from rest_framework import serializers

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('title', 'content', 'is_featured') # if not declared, all fields of the model will be shown

In this tutorial we have used ModelSerializer, more on this.

4. Views

A view function, or view for short, is a Python function that takes a Web request and returns a Web response.

# posts/api/views.py

from ..models import Post
from . import serializers
from rest_framework import generics, status
from rest_framework.response import Response

class PostListView(generics.ListAPIView):
    queryset = Post.objects.all()
    serializer_class = serializers.PostSerializer

As seen above, ListAPIView is used for read-only endpoints to represent a collection of model instances.

In this code snippet, we use generics view methods from the rest_framework, more on this.

5. URLs

This is where we setup our routes or URL paths to our designated views in which we expect specific responses for each.

# posts/urls.py

from django.urls import path
from . import views
from .api import views

urlpatterns = [
    path('', views.PostListView.as_view(), name=None)
]

6. Finalizing Setup

Ensure that the rest_framework is added to our project's apps.

# djangoapi/blog/blog/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework', # Add it here
    'posts'
]

7. Django Admin

Since we haven't setup our POST requests yet, we will be populating the database through django's admin panel.

To do that, create a superuser account admin with password 1234password.

$ python manage.py createsuperuser --email [email protected] --username admin

Password:
Password (again):
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

Register the model in the admin panel.

# posts/admin.py

from django.contrib import admin
from .models import Post

# Register your models here.
admin.site.register(Post)

That's it. Visit the admin panel and update posts model's records. More on this.

8. Testing our API

$ python manage.py runserver
GET /api/v1/posts/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "title": "Example Post #1",
        "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        "is_featured": false
    },
    {
        "title": "Example Post #2",
        "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        "is_featured": true
    }
]

Great. Now it's time for us to update our views and finish the standard CRUD operations.

9. Adding more views

POST is a method used for creating (sometimes updating) a resource in the database.

# posts/api/views.py

from ..models import Post
from . import serializers
from rest_framework import generics, status
from rest_framework.response import Response

class PostCreateView(generics.CreateAPIView):
    queryset = Post.objects.all()
    serializer_class = serializers.PostSerializer

    def create(self, request, *args, **kwargs):
        super(PostCreateView, self).create(request, args, kwargs)
        response = {"status_code": status.HTTP_200_OK,
                    "message": "Successfully created",
                    "result": request.data}
        return Response(response)

Most often, we separate List and Create view classes when we want to expose a list of data set while easily preventing a certain request to POST or create a resource in the database for that specific List view.

Usecase always varies for apps, you are opt to use ListCreateAPIView or even ViewSets for combining the logic for a set of related views.

Optional: Since we want to display the data in a more systematic way, we override create method and map our inline custom response handler.

Adding more views with methods GET, PATCH, DELETE to handle a specific blog post detail.

class PostDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Post.objects.all()
    serializer_class = serializers.PostSerializer

    def retrieve(self, request, *args, **kwargs):
        super(PostDetailView, self).retrieve(request, args, kwargs)
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data
        response = {"status_code": status.HTTP_200_OK,
                    "message": "Successfully retrieved",
                    "result": data}
        return Response(response)

    def patch(self, request, *args, **kwargs):
        super(PostDetailView, self).patch(request, args, kwargs)
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data
        response = {"status_code": status.HTTP_200_OK,
                    "message": "Successfully updated",
                    "result": data}
        return Response(response)

    def delete(self, request, *args, **kwargs):
        super(PostDetailView, self).delete(request, args, kwargs)
        response = {"status_code": status.HTTP_200_OK,
                    "message": "Successfully deleted"}
        return Response(response)

10. Updating URLs

# posts/urls.py

from django.urls import path
from . import views
from .api import views

urlpatterns = [
    path('', views.PostListView.as_view(), name=None),
    path('create/', views.PostCreateView.as_view(), name=None),
    path('<int:pk>/', views.PostDetailView.as_view(), name=None)
]

Now you can send requests to your API via Postman, your app or do a GETrequests from your browser, examples:

POST /api/v1/posts/create/
HTTP 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "status_code": 200,
    "message": "Successfully created",
    "result": {
        "csrfmiddlewaretoken": "rnSUN3XOIghnXA0yKghnQgxg0do39xhorYene5ALw3gWGThK5MjG6YjL8VUb7v2h",
        "title": "Creating a resource",
        "content": "Howdy mate!"
    }
}
GET /api/v1/posts/1/
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "status_code": 200,
    "message": "Successfully retrieved",
    "result": {
        "title": "Sample Post",
        "content": "Sample Post Content",
        "is_featured": false
    }
}

That's it. You have successfully managed to develop RESTful APIs with DRF! Cheers!

Source code

Available on GitHub.