Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Django RESTful Web Services
Django RESTful Web Services

Django RESTful Web Services: The easiest way to build Python RESTful APIs and web services with Django

Arrow left icon
Profile Icon Gaston C. Hillar
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.1 (8 Ratings)
Paperback Jan 2018 326 pages 1st Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Gaston C. Hillar
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.1 (8 Ratings)
Paperback Jan 2018 326 pages 1st Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Django RESTful Web Services

Installing the Required Software and Tools

In this chapter, we will start our journey towards creating RESTful Web Services with Python and its most popular web framework: Django. Python is one of the most popular and versatile programming languages. There are thousands of Python packages, which allow you to extend Python capabilities to any kind of domain you can imagine. You can work with Django and packages to easily build simple and complex RESTful Web Services with Python that can run on your favorite platform.

We will leverage your existing knowledge of Python and all of its packages to code the different pieces of your RESTful Web Services and their ecosystem. We will use object-oriented features to create code that is easier to maintain, understand, and reuse. We don't need to learn another programming language, we can use the one we already know and love: Python.

In this chapter, we will install and configure the environments and the required software and tools to create RESTful Web Services with Django and Django REST framework. We will learn the necessary steps in Linux, macOS, and Windows. We will gain an understanding of the following:

  • Creating a virtual environment with Python 3.x and PEP 405
  • Understanding the directory structure for a virtual environment
  • Activating the virtual environment
  • Deactivating the virtual environment
  • Installing Django and Django REST framework in an isolated environment
  • Creating an app with Django
  • Understanding Django folders, files, and configurations
  • Installing Curl
  • Installing HTTPie
  • Installing the Postman REST client
  • Installing Stoplight
  • Installing iCurlHTTP

Creating a virtual environment with Python 3.x and PEP 405

Throughout this book, we will be working with different packages and libraries to create RESTful Web Services, and therefore it is convenient to work with Python virtual environments. Python 3.3 introduced lightweight virtual environments and they were improved in Python 3.4. We will work with these virtual environments, and therefore you will need Python 3.4 or greater. You can read more information about PEP 405 Python Virtual Environment, that introduced the venv module, here: https://www.python.org/dev/peps/pep-0405. All the examples in this book were tested on Python 3.6.2 on Linux, macOS, and Windows.

In case you decide to use the popular virtualenv (https://pypi.python.org/pypi/virtualenv) third-party virtual environment builder or the virtual environment options provided by your Python IDE, you just have to make sure that you activate your virtual environment with the appropriate mechanism whenever it is necessary to do so, instead of following the step explained to activate the virtual environment generated with the venv module integrated in Python.

Each virtual environment we create with venv is an isolated environment and it will have its own independent set of installed Python packages in its site directories (folders). When we create a virtual environment with venv in Python 3.4 and greater, pip is included in the new virtual environment. In Python 3.3, it was necessary to manually install pip after creating the virtual environment. Note that the instructions provided are compatible with Python 3.4 or greater, including Python 3.6.2.

In order to create a lightweight virtual environment, the first step is to select the target folder or directory for it. The following is the path we will use in the example for Linux and macOS.

The target folder for the virtual environment will be the HillarDjangoREST/01 folder within our home directory. For example, if our home directory in macOS or Linux is /Users/gaston, the virtual environment will be created within /Users/gaston/HillarDjangoREST/01. You can replace the specified path with your desired path in each command:

    ~/HillarDjangoREST/01

The following is the path we will use in the example for Windows. The target folder for the virtual environment will be the HillarDjangoREST\01 folder within our user profile folder. For example, if our user profile folder is C:\Users\gaston, the virtual environment will be created within C:\Users\gaston\HillarDjangoREST\01. You can replace the specified path with your desired path in each command:

    %USERPROFILE%\HillarDjangoREST\01

In Windows PowerShell, the previous path would be as follows:

    $env:userprofile\HillarDjangoREST\01

Now, we will create a new virtual environment with venv. In order to do so, we have to use the -m option followed by the venv module name and the desired path to make Python run this module as a script and create a virtual environment in the specified path. The instructions are different depending on the platform in which we are creating the virtual environment.

Open Terminal in Linux or macOS and execute the following command to create a virtual environment:

    python3 -m venv ~/HillarDjangoREST/01

In Windows, in Command Prompt, execute the following command to create a virtual environment:

    python -m venv %USERPROFILE%\HillarDjangoREST\01

If you want to work with Windows PowerShell, execute the following command to create a virtual environment:

    python -m venv $env:userprofile\HillarDjangoREST\01

None of the previous commands produce any output. The script created the specified target folder and installed pip by invoking ensurepip because we didn't specify the --without-pip option.

Understanding the directory structure for a virtual environment

The specified target folder has a new directory tree that contains Python executable files and other files that indicate it is a PEP405 virtual environment.

In the root directory for the virtual environment, the pyenv.cfg configuration file specifies different options for the virtual environment and its existence is an indicator that we are in the root folder for a virtual environment. In Linux and macOS, the folder will have the following main subfolders: bin, include, lib, lib/python3.6, and lib/python3.6/site-packages. In Windows, the folder will have the following main subfolders: Include, Lib, Lib\site-packages, and Scripts. The directory trees for the virtual environment in each platform are the same as the layout of the Python installation on these platforms.

The following diagram shows the folders and files in the directory trees generated for the 01 virtual environments in macOS and Linux platforms:

The following diagram shows the main folders in the directory trees generated for the virtual environment in Windows:

After we activate the virtual environment, we will install third-party packages into the virtual environment and the modules will be located in the lib/python3.6/site-packages or Lib\site-packages folder, based on the platform. The executables will be copied in the bin or Scripts folder, based on the platform. The packages we install won't make changes to other virtual environments or our base Python environment.

Activating the virtual environment

Now that we have created a virtual environment, we will run a platform-specific script to activate it. After we activate the virtual environment, we will install packages that will only be available in this virtual environment. This way, we will work with an isolated environment in which all the packages we install won't affect our main Python environment.

Note that the results of this command will be accurate if you don't start a different shell than the default shell in the terminal session. If you have doubts, check your terminal configuration and preferences. Run the following command in the Terminal in Linux or macOS:

    echo $SHELL

The command will display the name of the shell you are using in the Terminal. In macOS, the default is /bin/bash and this means you are working with the bash shell. Depending on the shell, you must run a different command to activate the virtual environment in Linux or macOS.

If your Terminal is configured to use the bash shell in Linux or macOS, run the following command to activate the virtual environment. The command also works for the zsh shell:

    source ~/HillarDjangoREST/01/bin/activate

If your Terminal is configured to use either the csh or tcsh shell, run the following command to activate the virtual environment:

    source ~/HillarDjangoREST/01/bin/activate.csh

If your Terminal is configured to use the fish shell, run the following command to activate the virtual environment:

    source ~/HillarDjangoREST/01/bin/activate.fish

After you activate the virtual environment, Command Prompt will display the virtual environment root folder name enclosed in parentheses as a prefix of the default prompt to remind us that we are working in the virtual environment. In this case, we will see (01) as a prefix for the Command Prompt because the root folder for the activated virtual environment is 01.

The following screenshot shows the virtual environment activated in a macOS Sierra Terminal with a bash shell, after executing the previously shown commands:

As we can see from the previous screenshot, the prompt changed from

Gastons-MacBook-Pro:~ gaston$ to (01) Gastons-MacBook-Pro:~ gaston$ after the activation of the virtual environment.

In Windows, you can run either a batch file in the Command Prompt or a Windows PowerShell script to activate the virtual environment.

If you prefer Command Prompt, run the following command in the Windows command line to activate the virtual environment:

    %USERPROFILE%\HillarDjangoREST\01\Scripts\activate.bat

The following screenshot shows the virtual environment activated in Windows 10 Command Prompt, after executing the previously shown commands:

As we can see from the previous screenshot, the prompt changed from C:\Users\gaston to (01) C:\Users\gaston after the activation of the virtual environment.

If you prefer Windows PowerShell, launch it and run the following commands to activate the virtual environment. Note that you must have scripts execution enabled in Windows PowerShell to be able to run the script:

    cd $env:USERPROFILE
    HillarDjangoREST\01\Scripts\Activate.ps1

If you receive an error similar to the following lines, it means that you don't have scripts execution enabled:

    C:\Users\gaston\HillarDjangoREST\01\Scripts\Activate.ps1 : File C:\Users\gaston\HillarDjangoREST\01\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at
    http://go.microsoft.com/fwlink/?LinkID=135170.
    At line:1 char:1
    + C:\Users\gaston\HillarDjangoREST\01\Scripts\Activate.ps1
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : SecurityError: (:) [], PSSecurityException
        + FullyQualifiedErrorId : UnauthorizedAccess
  

The Windows PowerShell default execution policy is Restricted. This policy allows the execution of individual commands but it doesn't run scripts. Thus, in case you want to work with Windows PowerShell, you will have to change the policy to allow the execution of scripts. It is very important to make sure that you understand the risks of the Windows PowerShell execution policies that allow you to run unsigned scripts. For more information about the different policies, check the following web page: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-6.

The following screenshot shows the virtual environment activated in a Windows 10 PowerShell, after executing the previously shown commands:

Deactivating the virtual environment

It is extremely easy to deactivate a virtual environment generated by the previously explained process. The deactivation will remove all the changes made in the environment variables and will change the prompt back to its default message. Once you deactivate a virtual environment, you will go back to the default Python environment.

In macOS or Linux, just type deactivate and press Enter.

In a Windows Command Prompt, you have to run the deactivate.bat batch file included in the Scripts folder. In our example, the full path for this file is %USERPROFILE%\HillarDjangoREST\01\Scripts\deactivate.bat.

In Windows PowerShell, you have to run the Deactivate.ps1 script in the Scripts folder. In our example, the full path for this file is $env:userprofile\HillarDjangoREST\01\Scripts\Deactivate.ps1. Remember that you must have scripts execution enabled in Windows PowerShell to be able to run the script.

The instructions in the next sections assume that the virtual environment we have created is activated.

Installing Django and Django REST frameworks in an isolated environment

We have created and activated a lightweight virtual environment. It is time to run many commands that will be the same for either Linux, macOS, or Windows.

First, run the following command to install the Django web framework:

pip install django==1.11.5

The last lines of the output will indicate that the django package has been successfully installed. The process will also install the pytz package that provides world time zone definitions. Take into account that you may also see a notice to upgrade pip. The next lines show a sample of the four last lines of the output generated by a successful pip installation:

Collecting django
Collecting pytz (from django)
Installing collected packages: pytz, django
Successfully installed django-1.11.5 pytz-2017.2

Now that we have installed the Django web framework, we can install Django REST framework. Django REST framework works on top of Django and provides us with a powerful and flexible toolkit to build RESTful Web Services. We just need to run the following command to install this package:

pip install djangorestframework==3.6.4

The last lines for the output will indicate that the djangorestframework package has been successfully installed, as shown here:

Collecting djangorestframework
Installing collected packages: djangorestframework
Successfully installed djangorestframework-3.6.4  

After following the previous steps, we will have Django REST framework 3.6.4 and Django 1.11.5 installed in our virtual environment. We will install additional packages as we need them in the forthcoming chapters.

Creating an app with Django

Now, we will create our first app with Django and we will analyze the directory structure that Django creates. First, go to the root folder for the virtual environment: 01.

In Linux or macOS, enter the following command:

cd ~/HillarDjangoREST/01

If you prefer Command Prompt, run the following command in the Windows command line:

cd /d %USERPROFILE%\HillarDjangoREST\01

If you prefer Windows PowerShell, run the following command in Windows PowerShell:

cd /d $env:USERPROFILE\HillarDjangoREST\01  

In Linux or macOS, run the following command to create a new Django project named restful01. The command won't produce any output:

python bin/django-admin.py startproject restful01  

In Windows, in either Command Prompt or PowerShell, run the following command to create a new Django project named restful01. The command won't produce any output:

python Scripts\django-admin.py startproject restful01  

The previous command creates a restful01 folder with other subfolders and Python files. Now, go to the recently created restful01 folder. Just execute the following command on any platform:

cd restful01

Then, run the following command to create a new Django app named toys within the restful01 Django project. The command won't produce any output:

python manage.py startapp toys

The previous command creates a new restful01/toys subfolder, with the following files:

  • views.py
  • tests.py
  • models.py
  • apps.py
  • admin.py
  • __init__.py

In addition, the restful01/toys folder will have a migrations subfolder with an __init__.py Python script. The following diagram shows the folders and files in the directory tree, starting at the restful01 folder with two subfolders - toys and restful01:

Understanding Django folders, files, and configurations

After we create our first Django project and then a Django app, there are many new folders and files. First, use your favorite editor or IDE to check the Python code in the apps.py file within the restful01/toys folder (restful01\toys in Windows). The following lines show the code for this file:

from django.apps import AppConfig 
 
 
class ToysConfig(AppConfig): 
    name = 'toys' 

The code declares the ToysConfig class as a subclass of the django.apps.AppConfig class that represents a Django application and its configuration. The ToysConfig class just defines the name class attribute and sets its value to 'toys'.

Now, we have to add toys.apps.ToysConfig as one of the installed apps in the restful01/settings.py file that configures settings for the restful01 Django project. I built the previous string by concatenating many values as follows: app name + .apps. + class name, which is, toys + .apps. + ToysConfig. In addition, we have to add the rest_framework app to make it possible for us to use Django REST framework.

The restful01/settings.py file is a Python module with module-level variables that define the configuration of Django for the restful01 project. We will make some changes to this Django settings file. Open the restful01/settings.py file and locate the highlighted lines that specify the strings list that declares the installed apps. The following code shows the first lines for the settings.py file. Note that the file has more code:

""" 
Django settings for restful01 project. 
 
Generated by 'django-admin startproject' using Django 1.11.5. 
 
For more information on this file, see 
https://docs.djangoproject.com/en/1.11/topics/settings/ 
 
For the full list of settings and their values, see 
https://docs.djangoproject.com/en/1.11/ref/settings/ 
""" 
 
import os 
 
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) 
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
 
 
# Quick-start development settings - unsuitable for production 
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ 
 
# SECURITY WARNING: keep the secret key used in production secret! 
SECRET_KEY = '+uyg(tmn%eo+fpg+fcwmm&x(2x0gml8)=cs@$nijab%)y$a*xe' 
 
# SECURITY WARNING: don't run with debug turned on in production! 
DEBUG = True 
 
ALLOWED_HOSTS = [] 
 
 
# Application definition 
 
INSTALLED_APPS = [ 
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
] 

Add the following two strings to the INSTALLED_APPS strings list and save the changes to the restful01/settings.py file:

  • 'rest_framework'
  • 'toys.apps.ToysConfig'

The following lines show the new code that declares the INSTALLED_APPS string list with the added lines highlighted and with comments to understand what each added string means. The code file for the sample is included in the hillar_django_restful_01 folder:

INSTALLED_APPS = [ 
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
    # Django REST framework 
    'rest_framework', 
    # Toys application 
    'toys.apps.ToysConfig', 
] 

This way, we have added Django REST framework and the toys application to our initial Django project named restful01.

Installing tools

Now, we will leave Django for a while and we will install many tools that we will use to interact with the RESTful Web Services that we will develop throughout this book.

We will use the following different kinds of tools to compose and send HTTP requests and visualize the responses throughout our book:

  • Command-line tools
  • GUI tools
  • Python code
  • Web browser
  • JavaScript code

You can use any other application that allows you to compose and send HTTP requests. There are many apps that run on tablets and smartphones that allow you to accomplish this task. However, we will focus our attention on the most useful tools when building RESTful Web Services with Django.

Installing Curl

We will start installing command-line tools. One of the key advantages of command-line tools is that you can easily run again the HTTP requests again after we have built them for the first time, and we don't need to use the mouse or tap the screen to run requests. We can also easily build a script with batch requests and run them.

As happens with any command-line tool, it can take more time to perform the first requests compared with GUI tools, but it becomes easier once we have performed many requests and we can easily reuse the commands we have written in the past to compose new requests.

Curl, also known as cURL, is a very popular open source command-line tool and library that allows us to easily transfer data. We can use the curl command-line tool to easily compose and send HTTP requests and check their responses.

In Linux or macOS, you can open a Terminal and start using curl from the command line.

In Windows, you have two options. You can work with curl in Command Prompt or you can decide to install curl as part of the Cygwin package installation option and execute it from the Cygwin terminal. You can read more about the Cygwin terminal and its installation procedure at: http://cygwin.com/install.html. Windows Powershell includes a curl alias that calls the Invoke-WebRequest command, and therefore, if you want to work with Windows Powershell with curl, it is necessary to remove the curl alias.

If you want to use the curl command within Command Prompt, you just need to download and unzip the latest version of the curl download page: https://curl.haxx.se/download.html. Make sure you download the version that includes SSL and SSH.

The following screenshot shows the available downloads for Windows. The Win64 - Generic section includes the versions that we can run in Command Prompt or Windows Powershell.

The Win64 x86_64.7zip file provides the binary version for curl version 7.55.1 with SSL and SSH support:

After you unzip the .7zip or .zip file you have downloaded, you can include the folder in which curl.exe is included in your path. For example, if you unzip the Win64 x86_64.7zip file, you will find curl.exe in the bin folder. The following screenshot shows the results of executing curl --version on  Command Prompt in Windows 10. The --version option makes curl display its version and all the libraries, protocols, and features it supports:

Installing HTTPie

Now, we will install HTTPie, a command-line HTTP client written in Python that makes it easy to send HTTP requests and uses a syntax that is easier than curl. By default, HTTPie displays colorized output and uses multiple lines to display the response details. In some cases, HTTPie makes it easier to understand the responses than the curl utility. However, one of the great disadvantages of HTTPie as a command-line utility is that it takes more time to load than curl, and therefore, if you want to code scripts with too many commands, you have to evaluate whether it makes sense to use HTTPie.

We just need to make sure we run the following command in the virtual environment we have just created and activated. This way, we will install HTTPie only for our virtual environment.

Run the following command in the terminal, Command Prompt, or Windows PowerShell to install the httpie package:

pip install --upgrade httpie

The last lines of the output will indicate that the httpie package has been successfully installed:

    Collecting httpie
    Collecting colorama>=0.2.4 (from httpie)
    Collecting requests>=2.11.0 (from httpie)
    Collecting Pygments>=2.1.3 (from httpie)
    Collecting idna<2.7,>=2.5 (from requests>=2.11.0->httpie)
    Collecting urllib3<1.23,>=1.21.1 (from requests>=2.11.0->httpie)
    Collecting chardet<3.1.0,>=3.0.2 (from requests>=2.11.0->httpie)
    Collecting certifi>=2017.4.17 (from requests>=2.11.0->httpie)
    Installing collected packages: colorama, idna, urllib3, chardet, certifi, requests, Pygments, httpie
    Successfully installed Pygments-2.2.0 certifi-2017.7.27.1 chardet-3.0.4 colorama-0.3.9 httpie-0.9.9 idna-2.6 requests-2.18.4 urllib3-1.22
  
If you don't remember how to activate the virtual environment that we created for this example, read the Activating the virtual environment section in this chapter.

Now, we will be able to use the http command to easily compose and send HTTP requests to our future RESTful Web Services build with Django. The following screenshot shows the results of executing http on Command Prompt in Windows 10. HTTPie displays the valid options and indicates that a URL is required:

Installing the Postman REST client

So far, we have installed two terminal-based or command-line tools to compose and send HTTP requests to our Django development server: cURL and HTTPie. Now, we will start installing Graphical User Interface (GUI) tools.

Postman is a very popular API testing suite GUI tool that allows us to easily compose and send HTTP requests, among other features. Postman is available as a standalone app in Linux, macOS, and Windows. You can download the versions of the Postman app from the following URL: https://www.getpostman.com.

You can download and install Postman for free to compose and send HTTP requests to the RESTful Web Services we will build throughout this book. You just need to sign up to Postman. We won't be using any of the paid features provided by either Postman Pro or Postman Enterprise in our examples. All the instructions work with Postman 5.2.1 or greater.

The following screenshot shows the HTTP GET request builder in Postman:

Installing Stoplight

Stoplight is a very useful GUI tool that focuses on helping architects and developers to model complex APIs. If we need to consume our RESTful Web Service in many different programming languages, we will find Stoplight extremely helpful. Stoplight provides an HTTP request maker that allows us to compose and send requests and generate the necessary code to make them in different programming languages, such as JavaScript, Swift, C#, PHP, Node, and Go, among others.

Stoplight provides a web version and is also available as a standalone app in Linux, macOS, and Windows. You can download the versions of Stoplight from the following URL: http://stoplight.io/.

The following screenshot shows the HTTP GET request builder in Stoplight with the code generation at the bottom:

Installing iCurlHTTP

We can also use apps that can compose and send HTTP requests from mobile devices to work with our RESTful Web Services. For example, we can work with the iCurlHTTP app on iOS devices such as iPad and iPhone: https://itunes.apple.com/us/app/icurlhttp/id611943891. On Android devices, we can work with the HTTP Request app: https://play.google.com/store/apps/details?id=air.http.request&hl=en.

The following screenshot shows the UI for the iCurlHTTP app running on an iPad Pro:

At the time of writing, the mobile apps that allow you to compose and send HTTP requests do not provide all the features you can find in Postman or command-line utilities.

Test your knowledge

Let's see whether you can answer the following questions correctly:

  1. After we activate a virtual environment, all the packages we install with pip are available:
    1. For all the virtual environments available in the computer or device that is running Python
    2. Only for the activated virtual environment
    3. For all the virtual environments created by the current user
  2. HTTPie is a:
    1. Command-line HTTP server written in Python that makes it easy to create a RESTful Web Server

    2. Command-line utility that allows us to run queries against an SQLite database
    3. Command-line HTTP client written in Python that makes it easy to compose and send HTTP requests
  3. Which of the following commands creates a new app named books in Django?
    1. django startapp books
    2. python django.py startapp books
    3. python manage.py startapp books
  4. In Django, a subclass of which of the following classes represents a Django application and its configuration?
    1.  django.apps.AppConfig
    2. django.application.configuration
    3. django.config.App
  5. Which of the following strings must be added to the INSTALLED_APPS string list in the settings.py file to enable Django REST framework?
    1. 'rest_framework'
    2. 'django_rest_framework'
    3. 'Django_REST_framework'

The rights answers are included in the Appendix, Solutions.

Summary

In this chapter, we learned the advantages of working with lightweight virtual environments in Python and we set up a virtual environment with Django and Django REST framework. We created an app with Django, we took a first look at the Django folders, files, and configurations, and we made the necessary changes to activate Django REST framework.

Then, we introduced and installed command-line and GUI tools that we will use to interact with the RESTful Web Services that we will design, code, test, and run in the forthcoming chapters.

Now that we have our environment ready to start working with Django REST framework, we will define the requirements for our first RESTful Web Service and we will work with models, migrations, serialization, and deserialization, which are the topics that we are going to discuss in the next chapter.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create efficient real-world RESTful web services with the latest Django framework
  • Authenticate, secure, and integrate third-party packages efficiently in your Web Services
  • Leverage the power of Python for faster Web Service development

Description

Django is a Python web framework that makes the web development process very easy. It reduces the amount of trivial code, which simplifies the creation of web applications and results in faster development. It is very powerful and a great choice for creating RESTful web services. If you are a Python developer and want to efficiently create RESTful web services with Django for your apps, then this is the right book for you. The book starts off by showing you how to install and configure the environment, required software, and tools to create RESTful web services with Django and the Django REST framework. We then move on to working with advanced serialization and migrations to interact with SQLite and non-SQL data sources. We will use the features included in the Django REST framework to improve our simple web service. Further, we will create API views to process diverse HTTP requests on objects, go through relationships and hyperlinked API management, and then discover the necessary steps to include security and permissions related to data models and APIs. We will also apply throttling rules and run tests to check that versioning works as expected. Next we will run automated tests to improve code coverage. By the end of the book, you will be able to build RESTful web services with Django.

Who is this book for?

This book is for Python developers who want to create RESTful web services with Django; you need to have a basic working knowledge of Django but no previous experience with RESTful web services is required.

What you will learn

  • • The best way to build a RESTful Web Service or API with Django and the Django REST Framework
  • • Develop complex RESTful APIs from scratch with Django and the Django REST Framework
  • • Work with either SQL or NoSQL data sources
  • • Design RESTful Web Services based on application requirements
  • • Use third-party packages and extensions to perform common tasks
  • • Create automated tests for RESTful web services
  • • Debug, test, and profile RESTful web services with Django and the Django REST Framework

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 25, 2018
Length: 326 pages
Edition : 1st
Language : English
ISBN-13 : 9781788833929
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 25, 2018
Length: 326 pages
Edition : 1st
Language : English
ISBN-13 : 9781788833929
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 111.97
Django Design Patterns and Best Practices
€36.99
Django 2 by Example
€41.99
Django RESTful Web Services
€32.99
Total 111.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Installing the Required Software and Tools Chevron down icon Chevron up icon
Working with Models, Migrations, Serialization, and Deserialization Chevron down icon Chevron up icon
Creating API Views Chevron down icon Chevron up icon
Using Generalized Behavior from the APIView Class Chevron down icon Chevron up icon
Understanding and Customizing the Browsable API Feature Chevron down icon Chevron up icon
Working with Advanced Relationships and Serialization Chevron down icon Chevron up icon
Using Constraints, Filtering, Searching, Ordering, and Pagination Chevron down icon Chevron up icon
Securing the API with Authentication and Permissions Chevron down icon Chevron up icon
Applying Throttling Rules and Versioning Management Chevron down icon Chevron up icon
Automating Tests Chevron down icon Chevron up icon
Solutions Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.1
(8 Ratings)
5 star 25%
4 star 25%
3 star 0%
2 star 37.5%
1 star 12.5%
Filter icon Filter
Top Reviews

Filter reviews by




Vicente Marçal Jun 11, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excelente tratamento apresentando de forma prática como utilizar o Django com Django Rest Framework para a criação de RESTful APIs. Não deve faltar na biblioteca do Desenvolvedor Python/Django.
Amazon Verified review Amazon
Cliente Amazon2 Apr 13, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Utile per capire le API rest su Django rest framework, ovviamente va fatta qualche modifica a livello di codice per fare funzionare il progetto, ma niente di complesso. Consigliato
Amazon Verified review Amazon
Ryan McGuinness Apr 02, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a great book, and a much needed supplement for the online documentation. There are several more advanced topics that are not covered and require a lot of digging. Otherwise a great read with very clear step-by-step instructions.
Amazon Verified review Amazon
Amazon Customer May 15, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Great book with lots of examples. I would definitely recommend it.I would've liked to see a Django project with more than one app. I also would've liked to see a more thorough deployment strategy.
Amazon Verified review Amazon
EG Jun 02, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
The book is a shallow introduction to Django Restful API. The approach the author took is not educational. He put a bunch of code at the beginning of a chapter and devote the rest of the chapter to give poor explanations for the written code. If you have to read this book (unfortunately at the moment there are not many alternatives) I recommend you to get an introduction to APIs from somewhere else. Honestly, simply skip the first 7 chapters of the book and check out the official introduction instead. Last three chapters have some value though.Author loves copy-and-paste. Here is just one example excerpt (out of many) from book:"The PilotCompetitionSerializer class declares a pilot attribute that holds an instance of serializers.SlugRelatedField with its queryset argument set to Pilot.objects.all() and its slug_field argument set to 'name'. We created the pilot field as a models.ForeignKey instance in the Competition model and we want to display the Pilot's name as the description (slug field) for the related Pilot.The PilotCompetitionSerializer class declares a drone attribute that holds an instance of serializers.SlugRelatedField with its queryset argument set to Drone.objects.all() and its slug_field argument set to 'name'. We created the drone field as a models.ForeignKey instance in the Competition model and we want to display the drone's name as the description (slug field) for the related Drone."It is pretty boring to read such a book.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.