Django REST API

Submitted by Manuel Alba on Tue, 26/07/2016 - 14:06
django REST framework

Introduction

A very common way of obtaining information from different sources is with a REST API, which provides different API endpoints that are accessible in order to get certain data. Django REST Framework is a framework that allows us to easily create a Python REST API. Currently, this technology is used in various projects, such as the Racó API or the UOC índex project.

Installation

A good practice is to create a virtual environment with all the requirements to execute the REST API created with Django:

# Create the project directory
mkdir tutorial
cd tutorial
# Create a virtualenv to isolate our package dependencies locally
virtualenv env
source env/bin/activate # On Windows use `env\Scripts\activate`

Once we’ve installed the environment, we still need to install the necessary Python libraries in order to be able to use Django:

# Install Django and Django REST framework into the virtualenv
pip install django
pip install djangorestframework
# Set up a new project with a single application
django-admin.py startproject tutorial . # Note the trailing '.' character
cd tutorial
django-admin.py startapp quickstart

Now we have everything ready to start our Django project.

Project structure

Examining what has been created inside the tutorial folder, we can see how a Django project is structured:

  • env: virtual environment with the installed libraries and required files for the correct execution of the project.
  • tutorial: in this folder we can find the project’s configuration. We want to point out settings.py and urls.py, files that control the project’s configuration (installed applications, usable modules, supported database types…) and the available urls.
  • quickstart: in this folder we can find the quickstart application configuration.
  • manage.py: Python executable that allows to launch the API.

Application structure

Examining what has been created inside the quickstart folder, we can see how a Django project is structured:

  • models.py: file with information about the data models our application uses.
  • views.py: file that contains all the views used by the application.
  • tests.py: file to develop tests for the application.
  • migrations: directory responsible for detecting changes in the application databases.

It’s highly recommended to create additional files, in particular these two:

  • urls.py: file with the API’s possible urls or endpoints.
  • queries.py: file with the different calls to the databases.

Tutorial

Once we’re done with the installation as described at the Installation item, we’ll create a new endpoint to describe in more detail how Django works:

  1. We open the file tutorial/tutorial/settings.py and add the list INSTALLED_APPS ‘rest_framework’ and ‘quickstart’.
  2. We open the file tutorial/tutorial/urls.py and add the following url to the list urlpatterns: url(r’^quickstart/’, include(‘quickstart.urls’)). With this step, we’re done with the basic configuration of our quickstart application.
  3. Now we’ll add our first views to tutorial/quickstart/views.py:
    def index(request):
        return HttpResponse("Hello, world. You're at the quickstartapp index.")
    class Example(APIView):
    """
    Returns data from the football player Antoine Griezmann
    """
        def get(self, request):
            data = {'Player': 'Antoine griezmann','Team': 'Atlético de Madrid', 'Age': 25}
            return HttpResponse(json.dumps(data, indent=4, sort_keys=True), content_type="application/json")
    
  4. We go to /tutorial/quickstart and create the file urls.py:
    from django.conf.urls import url
    from . import views
    urlpatterns = [
        url(r'^index/', views.index, ),
        url(r'^griezmann/', views.Example.as_view(), name="'example'),
    ]
    
  5. We go to /tutorial and execute python manage.py runserver (it runs on port 8000 by default) and we verify our new enpoint is functioning. When calling the endpoint http://localhost:8000/quickstart/griezmann/ we should get a result similar to this one:
    {
    "Age": 25,
    "Player": "Antoine Griezmann",
    "Team": "Atletico de Madrid"
    }

This is only a small example where the data is generated every time we access the corresponding view. If we created a queries.py file, we’d be able to define a more complex way of obtaining the data, so that each time a certain view were called the corresponding data would be looked for at a given database.

To summarize

We’ve seen how to start developing a Django REST API that allows for a very simple development but at the same time powerful and easily scalable. You can find the official framework documentation at: http://www.django-rest-framework.org/

Follow us on

Els nostres articles del bloc d'inLab FIB

         
         

inLab FIB incorporates esCert

Icona ESCERT

inLab is member of