Development of APIs with Django REST Framework
Tags: api, python, django, development
Published: 2019-11-08 12:47:25

---
title: Development of APIs with Django REST Framework
published: true
cover_image: https://thepracticaldev.s3.amazonaws.com/i/umc4vt86sjat5pedcpx0.png
description: 
tags: API, Python,  Django, Development
canonical_url: https://djangostars.com/blog/rest-apis-django-development/
---
If you know the basics of the field you work in, you can master any technology, reach higher levels as developer, and create better products. In this article, we’ll talk about building APIs and how to do it, step by step. I believe this is going to be useful for all beginner Django developers, as REST APIs are used in every application or piece of software to connect the backend and frontend parts. If you master this, you can build all kinds of products.
<h2>Why Use the Django REST Framework?</h2>
Many frameworks allow you to easily build APIs for blog applications, but we will use only one – the Django REST framework. It’s convenient in many ways and offers the following advantages:
<ul>
 	<li>Its <a href="https://restframework.herokuapp.com/">Web-browsable API</a> is a huge usability win for your developers.</li>
 	<li><a href="https://www.django-rest-framework.org/api-guide/authentication/">Authentication policies</a> include packages for <a href="https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth">OAuth1</a> and <a href="https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit">OAuth2</a>.</li>
 	<li><a href="https://www.django-rest-framework.org/api-guide/serializers/">Serialization</a> supports both <a href="https://www.django-rest-framework.org/api-guide/serializers#modelserializer">ORM</a> and <a href="https://www.django-rest-framework.org/api-guide/serializers#serializers">non-ORM</a> data sources.</li>
 	<li>It’s customizable all the way down. Just use <a href="https://www.django-rest-framework.org/api-guide/views#function-based-views">regular function-based views</a> if you don't need the <a href="https://www.django-rest-framework.org/api-guide/generic-views/">more</a> <a href="https://www.django-rest-framework.org/api-guide/viewsets/">powerful</a> <a href="https://www.django-rest-framework.org/api-guide/routers/">features</a>.</li>
 	<li>It has <a href="https://www.django-rest-framework.org/">extensive documentation</a> and <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">great community support</a>.</li>
 	<li>It’s used and trusted by internationally recognized companies including <a href="https://www.mozilla.org/en-US/about/">Mozilla</a>, <a href="https://www.redhat.com/">Red Hat</a>, <a href="https://www.heroku.com/">Heroku</a>, and <a href="https://www.eventbrite.co.uk/about/">Eventbrite</a>.</li>
</ul>

<h2>The Step-by-Step Guide To Your API</h2>
In this Django REST framework tutorial, we’ll go through all the stages of building an API in great detail.
<h3>Set up your development environment</h3>
First of all, you have to install<a href="https://github.com/pyenv/pyenv/wiki#suggested-build-environment"> Python dependencies</a> for your OS. If you’re using Windows, you can easily install Linux as your secondary OS using this <a href="https://tutorials.ubuntu.com/tutorial/tutorial-install-ubuntu-desktop#0">manual</a> or <a href="https://www.virtualbox.org/wiki/Downloads">VirtualBox</a>.

To proceed, use <a href="https://github.com/pyenv/pyenv#installation">pyenv</a>, a simple yet effective Python management tool. It’s our go-to helper. It allows us to change the global Python version, install multiple Python versions, set project-specific Python versions, and manage virtual Python environments.

If you’re using Mac OS or Linux, it should be easy to <a href="https://github.com/pyenv/pyenv#installation">install</a>:
<pre><code>$ git clone https://github.com/pyenv/pyenv.git ~/.pyenv</code></pre>
Define the environment variable <code>PYENV_ROOT</code> to point to the path where pyenv repo is cloned. Then, add <code>$PYENV_ROOT/bin</code> to your <code>$PATH</code> for access to the pyenv command-line utility.
<pre><code>$ echo 'export PYENV_ROOT="$HOME/.pyenv"' &gt;&gt; ~/.bashrc
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' &gt;&gt; ~/.bashrc</code></pre>
Add the pyenv unit to your shell to enable shims and autocompletion.
<pre><code>$ echo -e 'if command -v pyenv 1&gt;/dev/null 2&gt;&amp;1; then\n  eval "$(pyenv init -)"\nfi' &gt;&gt; ~/.bashrc</code></pre>
Restart your shell so the path changes take effect. Now, you can begin to use pyenv.
<pre><code>$ exec "$SHELL"</code></pre>
At this point, install the latest stable version of Python. Now this...
<pre><code>$ pyenv install 3.7.4</code></pre>
… and create an environment for your project.
<pre><code>$ pyenv virtualenv 3.7.4 blog</code></pre>
<h3>Create a Django Project</h3>
Now, we’ll create a project folder and navigate to the newly created directory.
<pre><code>$ mkdir projects &amp;&amp; cd projects</code></pre>
The next step is to create a Django project. There are several ways to do it.

Personally, I prefer to <a href="https://docs.djangoproject.com/en/2.2/ref/django-admin/#startproject">start projects</a> from a template and use the <a href="https://github.com/django-stars/backend-skeleton">Django Stars backend skeleton</a> that has been implemented in our <a href="https://djangostars.com/services/web-development/">web development company</a>. It’s a great tool, since…
<ul>
 	<li>Django projects are formatted according to the Django Stars Code Style requirements,</li>
 	<li>django-environ helps keep all configuration in the environment,</li>
 	<li>psycopg2 is the default database driver,</li>
 	<li>django-extensions/ipython/ipdb is used for debug purposes,</li>
 	<li>pytest with pylava are provided for testing, and</li>
 	<li>A redefined startapp command allows you to create apps according to <a href="https://codestyle.djangostars.com/">Django Stars Code Style</a> requirements.</li>
</ul>
Here’s the command that will help you start a project from a template:
<pre><code>$ curl https://be.skeletons.djangostars.com/startproject | bash</code></pre>
At the start, you will be offered several Python versions to work with. Select the 3.7 version of Python.

<img class="alignnone size-full wp-image-1593" src="https://djangostars.com/blog/uploads/2019/10/ds-be-skeleton.png" alt="django-rest-api-be-skeleton" width="1768" height="1059" />

Set the project name to django_blog.

Since we’re going to use the Django Rest Framework, we should select the 3rd option:

<img class="alignnone size-full wp-image-1592" src="https://djangostars.com/blog/uploads/2019/10/ds-be-skeleton2.png" alt="django-rest-api-example-be-skeleton" width="1768" height="1059" />

If you know you’ll need Celery for you project, you can also choose the first option and press OK.

Anyway, what we just did was create a project from a template. Let’s now navigate to the project name directory:
<pre><code>$ cd django_blog</code></pre>
This is what our project’s structure looks like:

{% gist https://gist.github.com/olegkovalov/cf0b48e9aa51c8a2dab9587a4b30f369 %}
<h3>Install packages with requirements</h3>
To run the project, we need to install some packages, which are defined in the <code>requirements/dev.txt.</code>
Thus, we install packages with requirements for local development.

Navigate to the API directory:
<pre><code>$ cd api</code></pre>
and install the dependencies.

If you need to add any other packages, just add your package to the dev.txt file for local development, or to common.txt if you need it to be installed on the server.

Next, we will have to add the Pillow package that isn’t included by default in the package we installed. Open the
<code>requirements/common.txt</code> file and add Pillow==6.1.0 to the end. Then run:
<pre><code>$ pip install -r requirements/dev.txt</code></pre>
This is the file that contains a list of all the packages that will be installed.
<h3>Bootstrap the Database</h3>
Our project needs a database. Most Django developers prefer to use PostgresQL for all environments – i.e., the, development, staging and production systems. Some people use SQLite for local development and PostgreSQL in production. Django ORM allows you to deal with both databases. I strongly recommend that you keep your development station and production as similar as possible and use the same database.

There are several ways to bootstrap a database:
<ul>
 	<li>Using SQLite</li>
</ul>
To make the database bootstrapping easier, we can use SQLite. It’s an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.

All you need to do is open the .env file and replace:

{% gist https://gist.github.com/olegkovalov/096f982a4b45839463e073cf471a0746 %}

with

{% gist https://gist.github.com/olegkovalov/7bb7a0745124107224dbb0ddec3d8b9b %}

Here, we use the <a href="https://django-environ.readthedocs.io/en/latest/">django-environ</a> package, which allows you to define the configuration depending on your environment. You can find out more about this approach through <a href="https://12factor.net/">The Twelve Factor App</a>.
<ul>
 	<li>Using PostgreSQL</li>
</ul>
PostgreSQL is a powerful, open-source object-relational database system. It uses and extends the SQL language, and has many features that allow you to safely store and scale the most complicated data workloads. This system is a bit more complicated than SQLite, so you might want to learn more <a href="https://www.postgresql.org/about/">about</a> it.

It’s much easier to install PostgreSQL with <a href="https://djangostars.com/blog/what-is-docker-and-how-to-use-it-with-python/">Docker</a> – an open-source tool that automates the deployment of an application inside a software container. If you’re not familiar with Docker yet, feel free to check out some <a href="https://docs.docker.com/install/">instructions</a> on how to install it and work with <a href="https://docs.docker.com/compose/install/">docker-compose</a>.

Then just open a new tab and run:
<pre><code>$ docker-compose -f build/docker-compose-dev.yml up</code></pre>
Next, we should apply initial migrations:
<pre><code>$ python manage.py migrate</code></pre>
This will apply all previously unapplied migrations to the database which comes with the Django installation.

<a href="https://github.com/olegkovalov/django_blog/commit/4f9b20bafc69fb686026d112592c549bd8b6e858">https://github.com/olegkovalov/django_blog/commit/4f9b20bafc69fb686026d112592c549bd8b6e858</a>
<h3>Create a Blog Application</h3>
At this point, we’ve already created a Django project, installed packages with requirements, and bootstrapped the database. Which means we can now finally create a blog application using the following command:
<pre><code>$ python manage.py startapp blog</code></pre>
By doing this, you’ve also created a new directory. It will be available in <code>apps/blog.</code>

Now, we should register our application in <code>‘INSTALLED_APPS’</code>.

Add ’blog’ to your <code>‘INSTALLED_APPS’</code> settings placed in <code>‘api/django_blog/settings/django.py’</code>
{% gist https://gist.github.com/olegkovalov/7e18b7130baf3541cfea94a69bb2f986 %}
<h2>Test-Driven Development (TDD) of APIs</h2>
As you may have already learned, test-driven development is an approach that focuses on writing tests before you start implementing the business logic of your application. Writing tests first requires you to really consider what do you want from the code. But apart from this, TDD has numerous other benefits:
<ol>
 	<li>Fast feedback and detailed specification;</li>
 	<li>Reduced time spent on reworking and time spent in the debugger;</li>
 	<li>Maintainable, flexible, and easily extensible code;</li>
 	<li>Shorter development time to market;</li>
 	<li>Increased developer’s productivity;</li>
 	<li>SOLID code; and</li>
 	<li>A clean interface.</li>
</ol>
Also, TDD tells you whether your last change (or refactoring) <em>broke previously working code</em>. Moreover, it forces <em>radical simplification of the code</em> – you will only write code in response to the requirements of the tests. Also, you're forced to write small classes focused on one thing only. Further on, it allows the design to <em>evolve and adapt</em> to your changing understanding of the problem.

The resulting unit tests are simple and act as documentation for the code. Since TDD use cases are written as tests, other developers can view the tests as examples of how the code is supposed to work.

Before we write tests for our API, let’s take a step back and look at HTTP and how it interacts with the Django REST Framework.

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP defines methods like GET, POST, PUT, DELETE, OPTIONS, and HEAD to indicate the desired action that should be performed on the resource you identify. These methods can be defined by the characteristics of safety and idempotency (you can find out more about this <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">here</a>). By agreement, REST APIs rely on these methods, so feel free to use the appropriate HTTP method for each type of action.

Let’s apply it to the resource ‘post’.
<img src="https://i.ibb.co/WtTLwzX/Screenshot.png" alt="Screenshot" border="0">
<h3>How to Write Tests</h3>
With the <a href="https://docs.python.org/3/library/unittest.html">unittests</a> framework, writing tests becomes very easy.

Open the<code>‘api/django_blog/apps/blog/tests/test_models.py’</code>file and add the following code:
{% gist https://gist.github.com/olegkovalov/aa0c029c00ae29f39269517b36eab55d %}

Open the<code>‘api/django_blog/apps/blog/models/post.py’</code>file, and define models for Post and Tags:
{% gist https://gist.github.com/olegkovalov/e9ddacb705b79fa9fdf7763a1acd26c4 %}

Our Post model inherits from <code>‘CoreModel’</code>, so fields and methods defined in <code>‘CoreModel’</code> can be added to the <code>‘Post’</code> model.

Now, let’s run our first test on the models we’ve created:
<pre><code>$ python manage.py test</code></pre>
{% gist https://gist.github.com/olegkovalov/13f0108a08d45d63b99934a9ed63b533 %}

This means that the test was run successfully.

Open<code>‘api/django_blog/apps/blog/tests/tests.py’</code>and add tests for your API:
{% gist https://gist.github.com/olegkovalov/2895a23a3f4a43b7a52860e58042098a %}
<h2>Serializers</h2>
A <a href="https://www.django-rest-framework.org/api-guide/serializers/#serializers">serializer</a> is a framework that allows complex data such as querysets and model instances to be converted to native Python data types. Then, these can then be easily rendered into <span style="color: #333333;">JSON, XML</span> or other content types. Serializers also work in the opposite direction – deserializing allows parsed data to be converted back into complex types after having validated the incoming data. The serializers in the REST framework work in a way similar to Django's Form and ModelForm classes.
<h3>Declare Serializers</h3>
Open<code>‘api/django_blog/apps/blog/rest_api/serializers/post.py’</code>and add:
{% gist https://gist.github.com/olegkovalov/27cf670dd205c81193a3eb6b3b6a9e15 %}

Now, we can use the <code>PostSerializer</code> to serialize a post, or list of posts.
{% gist https://gist.github.com/olegkovalov/3d8349fc890bc57411779fea352918cb %}

Open<code>‘api/django_blog/apps/blog/rest_api/views/blog_views.py'</code>and add the following code to define API view:
{% gist https://gist.github.com/olegkovalov/265e8c9e5c11197b8ea85c134ca431c3 %}

Add the URLs of your endpoints to

<code>‘api/django_blog/apps/blog/rest_api/urls.py’</code>.This will be the URL where your API will be available.
{% gist https://gist.github.com/olegkovalov/0298e6547070cca146d293f318451d74 %}

Open<code>‘api/urls.py’</code>and include the blog’s application URLs:
{% gist https://gist.github.com/olegkovalov/8ea27c5149ba9fbe4e6e2d4aa71bf7f0 %}
<h3>Run Tests</h3>
Now, you can test your API using the following command:
<pre><code>$ python manage.py test</code></pre>
{% gist https://gist.github.com/olegkovalov/a96fcf8509496032ed7bf4a6ba6a9b54 %}

Voila! The test has been completed successfully.
<h2>Browsable API</h2>
API may stand for Application Programming Interface, but humans have to be able to read the APIs, too – someone has to do the programming. Hence the <a href="https://www.django-rest-framework.org/topics/browsable-api/#the-browsable-api">browsable API</a>. With the Django REST Framework, you can generate a human-friendly HTML output for each resource when an HTML format is requested. These pages allow you to easily browse through resources, as well as build in forms to submit data to the resources using POST, PUT, and DELETE.

Let’s test our API with the browsable REST Framework interface. First, start the development server:
<pre><code>$ python manage.py runserver_plus</code></pre>
Then, open your browser of choice and visit this <a href="http://127.0.0.1:8000/api/v1/posts/">url</a>:

<img class="alignnone size-full wp-image-1591" src="https://djangostars.com/blog/uploads/2019/10/post-list-create-api.png" alt="django-rest-api-post-list-create" width="1768" height="1059" />

Create a new post with an image file. Fill out the fields “Title” and “Text”, choose an image file in the form at the bottom, and press “POST”. The page will reload with the new content.

<img class="alignnone size-full wp-image-1594" src="https://djangostars.com/blog/uploads/2019/10/create-a-post.png" alt="django-rest-framework" width="1768" height="1059" />

If you want to work with a real post, feel free to visit this <a href="http://127.0.0.1:8000/api/v1/posts/d6f814b3-9ebf-4221-ab33-54373f5896b5/">page</a>.
<h3>Versioning</h3>
Versioning is a vital part of API design that allows you to improve the representation for the resources of your API and alter behavior between different clients. The REST framework provides a number of different versioning schemes. Versioning is determined by the incoming client request, and may either be based on the request URL or the request headers.

In this example, we use the url path versioning approach.

Open <code>‘api/django_blog/settings/django.py’</code> and add:
{% gist https://gist.github.com/olegkovalov/fb2fd307bf328c40cd33908c8c1e1728 %}

If the response was changed and you decide to define a different API version, you might handle it as follows:
{% gist https://gist.github.com/olegkovalov/b65dd4bea889a1d1264380075be1174d %}
<h3>Documenting Your API</h3>
The REST framework provides built-in support for generating OpenAPI schemas. These can be used with tools that allow you to build API documentation.

The browsable API that the REST framework provides allows your API to be entirely self- describing. You can get the documentation for each API endpoint by simply visiting the URL in your browser.

However, there’s also a number of great third-party documentation packages available. For instance, let’s try to integrate <a href="https://github.com/axnsan12/drf-yasg">drf-yasg</a>. Its goal is to implement as much of the <a href="https://openapis.org/">OpenAPI</a> specification as possible (nested schemas, named models, response bodies, enum/pattern/min/max validators, form parameters, etc.) and generate documents that can be used with code-generation tools.

Open the terminal, and type in:
<pre><code>$ pip install -U drf-yasg</code></pre>
Open <code>‘api/django_blog/settings/django.py’</code> and add the INSTALLED_APPS <code>‘drf_yasg’</code> package:
{% gist https://gist.github.com/olegkovalov/4054f97d52522c58f779813f379ced9a %}

Also, we should include URLs, for generated documentation:
{% gist https://gist.github.com/olegkovalov/1efedebf06bfd95945439e7c7fe53769 %}

You can find the documentation on your API in <a href="http://127.0.0.1:8000/doc/">this document.</a>

<img class="alignnone size-full wp-image-1595" src="https://djangostars.com/blog/uploads/2019/10/api-post-list.png" alt="django-rest-api-post-list" width="1768" height="1059" />

If you want to implement new features or play around, feel free to clone or fork my <a href="https://github.com/olegkovalov/django_blog">git hub repo</a>.

Now, let’s see why what we’ve learned about why Django REST Framework is so practical for building APIs. The Django REST Framework (DRF) provides a large set of features:
<ul>
 	<li>Easy creation of resources with <a href="https://www.django-rest-framework.org/api-guide/generic-views/">Generic Views</a> – they allow you to quickly build API views that map closely to your database models;</li>
 	<li>An a<a href="https://www.django-rest-framework.org/api-guide/authentication/#authentication">uthentication</a> mechanism associates an incoming request with a set of identifying credentials;</li>
 	<li><a href="https://www.django-rest-framework.org/api-guide/permissions/">Permissions</a> grant access to any authenticated user, and deny access to any unauthenticated user;</li>
 	<li><a href="https://www.django-rest-framework.org/api-guide/throttling/">Throttling</a> indicates a temporary state, and is used to control the rate of requests that clients can make to an API;</li>
 	<li><a href="https://www.django-rest-framework.org/api-guide/caching/">Caching</a> through cache utilities provided by Django;</li>
 	<li><a href="https://www.django-rest-framework.org/api-guide/filtering/">Filtering</a> allows you to restrict the items that are returned in response;</li>
 	<li><a href="https://www.django-rest-framework.org/api-guide/pagination/">Pagination</a> allows you to choose how large result sets will be split into individual pages of data;</li>
 	<li><a href="https://www.django-rest-framework.org/api-guide/status-codes/">Status Codes</a> – the REST framework includes a set of named constants you can use to make your code more transparent and readable;</li>
 	<li><a href="https://www.django-rest-framework.org/api-guide/versioning/">Versioning</a> to alter behavior between different clients; and</li>
 	<li><a href="https://www.django-rest-framework.org/topics/browsable-api/">The Browsable API</a> enables you to read the APIs.</li>
</ul>
If you still have questions and would love to learn more, there’s plenty of great Django REST API tutorials <span style="font-weight: 400;">and</span> resources for self-improvement. Here’s a <a href="https://www.django-rest-framework.org/community/tutorials-and-resources/">reading list</a> our <a href="https://djangostars.com/company/team/">software development team</a> Django Stars highly recommends. And if by any chance you have to deal with nested objects, here’s a useful <a href="https://github.com/beda-software/drf-writable-nested">library</a> that might come in handy. Also, feel free to visit the <a href="https://github.com/olegkovalov/django_blog">django_blog repository</a> for ideas and inspiration. But as I said before, if you know your basics well, you can build upon this knowledge. And considering how universal APIs are, you’ll be able to work with any kind of product, which will make you an indispensable team member and a universal soldier of software development.

This guide about [how to develop APIs with Django REST Framework](https://djangostars.com/blog/rest-apis-django-development/) was originally posted on Django Stars blog. Written by Oleg Kovalyov - Software Engineer Lead at [Django Stars](https://djangostars.com/)