SlideShare a Scribd company logo
Django Restful Web Services Gaston C Hillar
download
https://ebookbell.com/product/django-restful-web-services-gaston-
c-hillar-52556306
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Django Restful Web Services 1st Edition Gaston C Hillar
https://ebookbell.com/product/django-restful-web-services-1st-edition-
gaston-c-hillar-33934172
Django Restful Web Services Gaston C Hillar
https://ebookbell.com/product/django-restful-web-services-gaston-c-
hillar-61031708
Building Versatile Mobile Apps With Python And Rest Restful Web
Services With Django And React 1st Edition Art Yudin
https://ebookbell.com/product/building-versatile-mobile-apps-with-
python-and-rest-restful-web-services-with-django-and-react-1st-
edition-art-yudin-52951278
Django 4 By Example Build Powerful And Reliable Python Web
Applications From Scratch 4th Antonio Mel
https://ebookbell.com/product/django-4-by-example-build-powerful-and-
reliable-python-web-applications-from-scratch-4th-antonio-mel-46085550
Django Javascript Integration Ajax And Jquery 1st Edition Jonathan
Hayward
https://ebookbell.com/product/django-javascript-integration-ajax-and-
jquery-1st-edition-jonathan-hayward-49052714
Django Standalone Apps Learn To Develop Reusable Django Libraries 1st
Edition Ben Lopatin
https://ebookbell.com/product/django-standalone-apps-learn-to-develop-
reusable-django-libraries-1st-edition-ben-lopatin-50195676
Django The Easy Way A Stepbystep Guide On Building Django Websites 2nd
Edition Samuli Natri
https://ebookbell.com/product/django-the-easy-way-a-stepbystep-guide-
on-building-django-websites-2nd-edition-samuli-natri-50200506
Django 10 Template Development Scott Newman
https://ebookbell.com/product/django-10-template-development-scott-
newman-50478114
Django In Action Meap V01 Chapters 1 To 5 Of 20 Christopher Trudeau
https://ebookbell.com/product/django-in-action-
meap-v01-chapters-1-to-5-of-20-christopher-trudeau-50864070
Django Restful Web Services Gaston C Hillar
Django Restful Web Services Gaston C Hillar
Preface
Python is definitely one of the most popular programming languages. It is
open source, multiplatform, and you can use it to develop any kind of
application, from websites and web services to artificial intelligence and
machine learning applications. You will always find a framework or a set
of packages in Python to make things easier for you in any domain. It is
extremely easy to work with Python and its most popular web framework,
Django, in the most important and popular cloud computing providers.
Hence, Python is an excellent choice for developing modern and scalable
RESTful Web Services that will run on the cloud.
REST (short for Representational State Transfer) is the architectural style
that has been driving modern and scalable web development recently. If
you want to be part of the world that builds complex web applications and
mobile apps, you will need to develop and interact with RESTful Web
Services. In many situations, you will have to design and develop a
RESTful Web Service from scratch and maintain the API over time. A
deep knowledge of RESTful Web Services is an essential skill for any
software development job.
This book covers everything you need to know to develop and test a
RESTful Web Service from scratch with the latest version of Django,
Django REST framework, and Python. You will work with real-life
examples in combination with Python packages that will allow you to
simplify tasks.
You will learn to use a huge set of tools to test and develop a uniform,
high-quality, and scalable RESTful Web Services. You will use object-
oriented programming and modern Python 3.6 code to favor code reuse
and simplify future maintenance. You will take advantage of automated
testing to ensure that the coded RESTful Web Services run as expected.
This book will allow you to create your own RESTful Web Services for
any domain with Django and Django REST framework in Python 3.6 or
greater. You will learn the process for the most popular Python platforms:
Linux, Windows, and macOS.
Who this book is for
This book is for Python developers who want to develop RESTful Web
Services, also known as RESTful web APIs, with Python 3.6 or greater,
and want to learn how to do it with the most popular Python web
framework—Django.
What this book covers
Chapter 1, Installing the Required Software and Tools, shows how to get
started in our journey toward creating RESTful Web Services with Python
and its most popular web framework—Django. We will install and
configure the environments, the software, and the tools required to create
RESTful Web Services with Django and Django REST framework. We
will learn the necessary steps in Linux, macOS, and Windows. We will
create our first app with Django, we will take a first look at the Django
folders, files, and configurations, and we will make the necessary changes
to activate Django REST framework. In addition, we will introduce and
install command-line and GUI tools that we will use to interact with the
RESTful Web Services that we will design, code, and test in the
forthcoming chapters.
Chapter 2, Working with Models, Migrations, Serialization, and
Deserialization, describes how to design a RESTful Web Service to
interact with a simple SQLite database and perform CRUD operations
with toys. We will define the requirements for our web service, and we
will understand the tasks performed by each HTTP method and the
different scopes. We will create a model to represent and persist toys and
execute migrations in Django to create the required tables in the database.
We will analyze the tables and learn how to manage the serialization of toy
instances into JSON representations with Django REST framework and
the reverse process.
Chapter 3, Creating API Views, is about executing the first version of a
simple Django RESTful Web Service that interacts with a SQLite
database. We will write API views to process diverse HTTP requests on a
collection of toys and on a specific toy. We will work with the following
HTTP verbs: GET, POST, and PUT. We will configure the URL patterns
list to route URLs to views. We will start the Django development server
and use command-line tools (curl and HTTPie) to compose and send
diverse HTTP requests to our RESTful Web Service. We will learn how
HTTP requests are processed in Django and our code. In addition, we will
work with Postman, a GUI tool, to compose and send other HTTP requests
to our RESTful Web Service.
Chapter 4, Using Generalized Behavior from the APIView Class, presents
different ways to improve our simple Django RESTful Web Service. We
will take advantage of many features included in the Django REST
framework to remove duplicate code and add many features for the web
service. We will use model serializers, understand the different accepted
and returned content types, and the importance of providing accurate
responses to the HTTP OPTIONS requests. We will make the necessary
changes to the existing code to enable diverse parsers and renderers. We
will learn how things work under the hoods in Django REST framework.
We will work with different content types and note how the RESTful Web
Service improves compared to its previous versions.
Chapter 5, Understanding and Customizing the Browsable API Feature,
explains how to use one of the additional features that Django REST
framework adds to our RESTful Web Service—the browsable API. We
will use a web browser to work with our first web service built with
Django. We will learn to make HTTP GET, POST, PUT, OPTIONS, and
DELETE requests with the browsable API. We will be able to easily test
CRUD operations with a web browser. The browsable API will allow us to
easily interact with our RESTful Web Service.
Chapter 6, Working with Advanced Relationships and Serialization, shows
how to define the requirements for a complex RESTful Web Service in
which we needed to work with drone categories, drones, pilots, and
competitions. We will create a new app with Django and configure the
new web service. We will define many-to-one relationships between the
models, and we will configure Django to work with a PostgreSQL
database. We will execute migrations to generate tables with relationships
between them. We will also analyze the generated database and configure
serialization and deserialization for the models. We will define hyperlinks
and work with class-based views. Then, we will take advantage of generic
classes and generic views that generalize and mix predefined behaviors.
We will use routings and endpoints and prepare our RESTful Web Service
to work with the browsable API. We will make many different HTTP
requests to create and retrieve resources that have relationships between
them.
Chapter 7, Using Constraints, Filtering, Searching, Ordering, and
Pagination, describes the usage of the browsable API feature to navigate
through the API with resources and relationships. We will add unique
constraints to improve the consistency of the models in our RESTful Web
Service. We will understand the importance of paginating results and
configure and test a global limit/offset pagination scheme with Django
REST framework. Then, we will create our own customized pagination
class to ensure that requests won't be able to require a huge number of
elements on a single page. We will configure filter backend classes and
incorporate code into the models to add filtering, searching, and ordering
capabilities to the class-based views. We will create a customized filter
and make requests to filter, search, and order results. Finally, we will use
the browsable API to test pagination, filtering, and ordering.
Chapter 8, Securing the API with Authentication and Permissions, presents
the differences between authentication and permissions in Django, Django
REST framework, and RESTful Web Services. We will analyze the
authentication classes included in Django REST framework out of the box.
We will follow the steps needed to provide security- and permissions-
related data to models.
We will work with object-level permissions via customized permission
classes and save information about users who make requests. We will
configure permission policies and compose and send authenticated
requests to understand how the permission policies work. We will use
command-line tools and GUI tools to compose and send authenticated
requests. We will browse the secure RESTful Web Service with the
browsable API feature and work with a simple token-based authentication
provided by Django REST framework to understand another way of
authenticating requests.
Chapter 9, Applying Throttling Rules and Versioning Management, focuses
on the importance of throttling rules and how we can combine them with
authentication and permissions in Django, Django REST framework, and
RESTful Web Services. We will analyze the throttling classes included in
Django REST framework out of the box. We will follow the necessary
steps to configure many throttling policies in Django REST framework.
We will work with global and scope-related settings. Then, we will use
command-line tools to compose and send many requests to test how the
throttling rules work. We will understand versioning classes and we will
configure a URL path versioning scheme to allow us to work with two
versions of our RESTful Web Service. We will use command-line tools
and the Browsable API to understand the differences between the two
versions.
Chapter 10, Automating Tests, shows how to automate tests for our RESTful
Web Services developed with Django and Django REST framework. We
will use different packages, tools, and configurations to perform tests. We
will write the first round of unit tests for our RESTful Web Service, run
them, and measure tests code coverage. Then, we will analyze tests code
coverage reports and write new unit tests to improve the test code
coverage. We will understand the new tests code coverage reports and
learn the benefits of a good test code coverage.
Appendix, Solutions, the right answers for the Test Your Knowledge sections
of each chapter are included in the appendix.
To get the most out of this
book
Any computer or device capable of running Python 3.6.3 or greater in
Linux, macOS, or Windows.
Any computer or device capable of running a modern web browser
compatible with HTML 5 and CSS 3 to work with the Browsable API
feature included in Django REST framework.
Download the example code
files
You can download the example code files for this book from your account
at www.packtpub.com. If you purchased this book elsewhere, you can visit www.p
acktpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
1. Log in or register at www.packtpub.com.
2. Select the SUPPORT tab.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box and follow the
onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract
the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/
PacktPublishing/Django-RESTful-Web-Services. We also have other code bundles
from our rich catalog of books and videos available at https://github.com/Pac
ktPublishing/. Check them out!
Download the color images
We also provide a PDF file that has color images of the
screenshots/diagrams used in this book. You can download it here: http://w
ww.packtpub.com/sites/default/files/downloads/DjangoRESTfulWebServices_ColorImages.
pdf.
Conventions used
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder
names, filenames, file extensions, pathnames, dummy URLs, user input,
and Twitter handles. Here is an example: "Mount the downloaded WebStorm-
10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
from django.shortcuts import render
# Create your views here.
When we wish to draw your attention to a particular part of a code block,
the relevant lines or items are set in bold:
from django.conf.urls import url, include
urlpatterns = [
url(r'^', include('drones.urls')),
url(r'^api-auth/', include('rest_framework.urls'))
]
Any command-line input or output is written as follows:
http :8000/toys/
curl -iX GET localhost:8000/toys/3
Bold: Indicates a new term, an important word, or words that you see
onscreen. For example, words in menus or dialog boxes appear in the text
like this. Here is an example: "Select System info from the Administration
panel."
Warnings or important notes appear like this.
Tips and tricks appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: Email feedback@packtpub.com and mention the book title
in the subject of your message. If you have questions about any aspect of
this book, please email us at questions@packtpub.com.
Errata: Although we have taken every care to ensure the accuracy of our
content, mistakes do happen. If you have found a mistake in this book, we
would be grateful if you would report this to us. Please visit www.packtpub.com
/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on
the Internet, we would be grateful if you would provide us with the
location address or website name. Please contact us at copyright@packtpub.com
with a link to the material.
If you are interested in becoming an author: If there is a topic that you
have expertise in and you are interested in either writing or contributing to
a book, please visit authors.packtpub.com.
Reviews
Please leave a review. Once you have read and used this book, why not
leave a review on the site that you purchased it from? Potential readers can
then see and use your unbiased opinion to make purchase decisions, we at
Packt can understand what you think about our products, and our authors
can see your feedback on their book. Thank you!
For more information about Packt, please visit : packtpub.com.
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/de
v/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.p
ython.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 HillarDjangoREST01
folder within our user profile folder. For example, if our user profile folder
is C:Usersgaston, the virtual environment will be created within
C:UsersgastonHillarDjangoREST01. You can replace the specified path with
your desired path in each command:
%USERPROFILE%HillarDjangoREST01
In Windows PowerShell, the previous path would be as follows:
$env:userprofileHillarDjangoREST01
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%HillarDjangoREST01
If you want to work with Windows PowerShell, execute the following
command to create a virtual environment:
python -m venv $env:userprofileHillarDjangoREST01
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, Libsite-
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
Libsite-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%HillarDjangoREST01Scriptsactivate.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:Usersgaston to (01) C:Usersgaston 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
HillarDjangoREST01ScriptsActivate.ps1
If you receive an error similar to the following lines, it means that you
don't have scripts execution enabled:
C:UsersgastonHillarDjangoREST01ScriptsActivate.ps1 : File C:UsersgastonHillarDjangoRE
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ C:UsersgastonHillarDjangoREST01ScriptsActivate.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%HillarDjangoREST01Scriptsdeactivate.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:userprofileHillarDjangoREST01ScriptsDeactivate.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%HillarDjangoREST01
If you prefer Windows PowerShell, run the following command in
Windows PowerShell:
cd /d $env:USERPROFILEHillarDjangoREST01
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 Scriptsdjango-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:
Django Restful Web Services Gaston C Hillar
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
(restful01toys 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://cyg
win.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: h
ttps://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,
Successfully installed Pygments-2.2.0 certifi-2017.7.27.1 chardet-3.0.4 colorama-0.3.9 httpie-
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:
Django Restful Web Services Gaston C Hillar
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/st
ore/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.
Working with Models,
Migrations, Serialization, and
Deserialization
In this chapter, we will define the requirements for our first RESTful Web
Service. We will start working with Django, Django REST framework,
Python, configurations, models, migrations, serialization, and
deserialization. We will create a RESTful Web Service that performs
CRUD (short for Create, Read, Update and Delete) operations on a
simple SQLite database. We will be:
Defining the requirements for our first RESTful Web Service
Creating our first model
Running our initial migration
Understanding migrations
Analyzing the database
Understanding Django tables
Controlling, serialization, and deserialization
Working with the Django shell and diving deeply into serialization
and deserialization
Defining the requirements for
our first RESTful Web Service
Imagine a team of developers working on a mobile app for iOS and
Android and requires a RESTful Web Service to perform CRUD
operations with toys. We definitely don't want to use a mock web service
and we don't want to spend time choosing and configuring an ORM (short
for Object-Relational Mapping). We want to quickly build a RESTful
Web Service and have it ready as soon as possible to start interacting with
it in the mobile app.
We really want the toys to persist in a database but we don't need it to be
production-ready. Therefore, we can use the simplest possible relational
database, as long as we don't have to spend time performing complex
installations or configurations.
Django REST framework, also known as DRF, will allow us to easily
accomplish this task and start making HTTP requests to the first version of
our RESTful Web Service. In this case, we will work with a very simple
SQLite database, the default database for a new Django REST framework
project.
First, we must specify the requirements for our main resource: a toy. We
need the following attributes or fields for a toy entity:
An integer identifier
A name
An optional description
A toy category description, such as action figures, dolls, or
Random documents with unrelated
content Scribd suggests to you:
Django Restful Web Services Gaston C Hillar
back
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Python Ireland Nov 2010 - RESTing with Django
PDF
Rest api with Python
PDF
Building an API with Django and Django REST Framework
PDF
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
PDF
Python RESTful webservices with Python: Flask and Django solutions
PDF
Free django
PDF
Lightweight Django 1st Edition Julia Elman
PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Python Ireland Nov 2010 - RESTing with Django
Rest api with Python
Building an API with Django and Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Python RESTful webservices with Python: Flask and Django solutions
Free django
Lightweight Django 1st Edition Julia Elman
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...

Similar to Django Restful Web Services Gaston C Hillar (20)

PDF
Creating Restful Web Services with restish
PPTX
Django with REST API Online Training - NareshIT
PPTX
REST Easy with Django-Rest-Framework
PDF
Django for mobile applications
PDF
UnRESTful APIs with Django
PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
PPTX
React django
PDF
API Design & Security in django
PPTX
Django rest framework
DOCX
Akash rajguru project report sem v
PDF
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
PDF
A python web service
PDF
Django REST Framework
DOCX
What is Full Stack with Django and how to start learning It.docx
PPTX
Django course
PPTX
Django Framework Interview Guide - Part 1
PDF
Django Rest Framework - Building a Web API
PDF
GDG Addis - An Introduction to Django and App Engine
PPTX
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
PDF
Django in Action (MEAP V01) Christopher Trudeau
Creating Restful Web Services with restish
Django with REST API Online Training - NareshIT
REST Easy with Django-Rest-Framework
Django for mobile applications
UnRESTful APIs with Django
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
React django
API Design & Security in django
Django rest framework
Akash rajguru project report sem v
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
A python web service
Django REST Framework
What is Full Stack with Django and how to start learning It.docx
Django course
Django Framework Interview Guide - Part 1
Django Rest Framework - Building a Web API
GDG Addis - An Introduction to Django and App Engine
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
Django in Action (MEAP V01) Christopher Trudeau
Ad

Recently uploaded (20)

PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
master seminar digital applications in india
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Computing-Curriculum for Schools in Ghana
PDF
Insiders guide to clinical Medicine.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Lesson notes of climatology university.
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
RMMM.pdf make it easy to upload and study
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
TR - Agricultural Crops Production NC III.pdf
PPH.pptx obstetrics and gynecology in nursing
O5-L3 Freight Transport Ops (International) V1.pdf
Sports Quiz easy sports quiz sports quiz
master seminar digital applications in india
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Computing-Curriculum for Schools in Ghana
Insiders guide to clinical Medicine.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Lesson notes of climatology university.
Pharmacology of Heart Failure /Pharmacotherapy of CHF
RMMM.pdf make it easy to upload and study
Module 4: Burden of Disease Tutorial Slides S2 2025
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
STATICS OF THE RIGID BODIES Hibbelers.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Ad

Django Restful Web Services Gaston C Hillar

  • 1. Django Restful Web Services Gaston C Hillar download https://ebookbell.com/product/django-restful-web-services-gaston- c-hillar-52556306 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Django Restful Web Services 1st Edition Gaston C Hillar https://ebookbell.com/product/django-restful-web-services-1st-edition- gaston-c-hillar-33934172 Django Restful Web Services Gaston C Hillar https://ebookbell.com/product/django-restful-web-services-gaston-c- hillar-61031708 Building Versatile Mobile Apps With Python And Rest Restful Web Services With Django And React 1st Edition Art Yudin https://ebookbell.com/product/building-versatile-mobile-apps-with- python-and-rest-restful-web-services-with-django-and-react-1st- edition-art-yudin-52951278 Django 4 By Example Build Powerful And Reliable Python Web Applications From Scratch 4th Antonio Mel https://ebookbell.com/product/django-4-by-example-build-powerful-and- reliable-python-web-applications-from-scratch-4th-antonio-mel-46085550
  • 3. Django Javascript Integration Ajax And Jquery 1st Edition Jonathan Hayward https://ebookbell.com/product/django-javascript-integration-ajax-and- jquery-1st-edition-jonathan-hayward-49052714 Django Standalone Apps Learn To Develop Reusable Django Libraries 1st Edition Ben Lopatin https://ebookbell.com/product/django-standalone-apps-learn-to-develop- reusable-django-libraries-1st-edition-ben-lopatin-50195676 Django The Easy Way A Stepbystep Guide On Building Django Websites 2nd Edition Samuli Natri https://ebookbell.com/product/django-the-easy-way-a-stepbystep-guide- on-building-django-websites-2nd-edition-samuli-natri-50200506 Django 10 Template Development Scott Newman https://ebookbell.com/product/django-10-template-development-scott- newman-50478114 Django In Action Meap V01 Chapters 1 To 5 Of 20 Christopher Trudeau https://ebookbell.com/product/django-in-action- meap-v01-chapters-1-to-5-of-20-christopher-trudeau-50864070
  • 6. Preface Python is definitely one of the most popular programming languages. It is open source, multiplatform, and you can use it to develop any kind of application, from websites and web services to artificial intelligence and machine learning applications. You will always find a framework or a set of packages in Python to make things easier for you in any domain. It is extremely easy to work with Python and its most popular web framework, Django, in the most important and popular cloud computing providers. Hence, Python is an excellent choice for developing modern and scalable RESTful Web Services that will run on the cloud. REST (short for Representational State Transfer) is the architectural style that has been driving modern and scalable web development recently. If you want to be part of the world that builds complex web applications and mobile apps, you will need to develop and interact with RESTful Web Services. In many situations, you will have to design and develop a RESTful Web Service from scratch and maintain the API over time. A deep knowledge of RESTful Web Services is an essential skill for any software development job. This book covers everything you need to know to develop and test a RESTful Web Service from scratch with the latest version of Django, Django REST framework, and Python. You will work with real-life examples in combination with Python packages that will allow you to simplify tasks. You will learn to use a huge set of tools to test and develop a uniform, high-quality, and scalable RESTful Web Services. You will use object- oriented programming and modern Python 3.6 code to favor code reuse and simplify future maintenance. You will take advantage of automated testing to ensure that the coded RESTful Web Services run as expected.
  • 7. This book will allow you to create your own RESTful Web Services for any domain with Django and Django REST framework in Python 3.6 or greater. You will learn the process for the most popular Python platforms: Linux, Windows, and macOS.
  • 8. Who this book is for This book is for Python developers who want to develop RESTful Web Services, also known as RESTful web APIs, with Python 3.6 or greater, and want to learn how to do it with the most popular Python web framework—Django.
  • 9. What this book covers Chapter 1, Installing the Required Software and Tools, shows how to get started in our journey toward creating RESTful Web Services with Python and its most popular web framework—Django. We will install and configure the environments, the software, and the tools required to create RESTful Web Services with Django and Django REST framework. We will learn the necessary steps in Linux, macOS, and Windows. We will create our first app with Django, we will take a first look at the Django folders, files, and configurations, and we will make the necessary changes to activate Django REST framework. In addition, we will introduce and install command-line and GUI tools that we will use to interact with the RESTful Web Services that we will design, code, and test in the forthcoming chapters. Chapter 2, Working with Models, Migrations, Serialization, and Deserialization, describes how to design a RESTful Web Service to interact with a simple SQLite database and perform CRUD operations with toys. We will define the requirements for our web service, and we will understand the tasks performed by each HTTP method and the different scopes. We will create a model to represent and persist toys and execute migrations in Django to create the required tables in the database. We will analyze the tables and learn how to manage the serialization of toy instances into JSON representations with Django REST framework and the reverse process. Chapter 3, Creating API Views, is about executing the first version of a simple Django RESTful Web Service that interacts with a SQLite database. We will write API views to process diverse HTTP requests on a collection of toys and on a specific toy. We will work with the following HTTP verbs: GET, POST, and PUT. We will configure the URL patterns list to route URLs to views. We will start the Django development server and use command-line tools (curl and HTTPie) to compose and send
  • 10. diverse HTTP requests to our RESTful Web Service. We will learn how HTTP requests are processed in Django and our code. In addition, we will work with Postman, a GUI tool, to compose and send other HTTP requests to our RESTful Web Service. Chapter 4, Using Generalized Behavior from the APIView Class, presents different ways to improve our simple Django RESTful Web Service. We will take advantage of many features included in the Django REST framework to remove duplicate code and add many features for the web service. We will use model serializers, understand the different accepted and returned content types, and the importance of providing accurate responses to the HTTP OPTIONS requests. We will make the necessary changes to the existing code to enable diverse parsers and renderers. We will learn how things work under the hoods in Django REST framework. We will work with different content types and note how the RESTful Web Service improves compared to its previous versions. Chapter 5, Understanding and Customizing the Browsable API Feature, explains how to use one of the additional features that Django REST framework adds to our RESTful Web Service—the browsable API. We will use a web browser to work with our first web service built with Django. We will learn to make HTTP GET, POST, PUT, OPTIONS, and DELETE requests with the browsable API. We will be able to easily test CRUD operations with a web browser. The browsable API will allow us to easily interact with our RESTful Web Service. Chapter 6, Working with Advanced Relationships and Serialization, shows how to define the requirements for a complex RESTful Web Service in which we needed to work with drone categories, drones, pilots, and competitions. We will create a new app with Django and configure the new web service. We will define many-to-one relationships between the models, and we will configure Django to work with a PostgreSQL database. We will execute migrations to generate tables with relationships between them. We will also analyze the generated database and configure serialization and deserialization for the models. We will define hyperlinks and work with class-based views. Then, we will take advantage of generic classes and generic views that generalize and mix predefined behaviors.
  • 11. We will use routings and endpoints and prepare our RESTful Web Service to work with the browsable API. We will make many different HTTP requests to create and retrieve resources that have relationships between them. Chapter 7, Using Constraints, Filtering, Searching, Ordering, and Pagination, describes the usage of the browsable API feature to navigate through the API with resources and relationships. We will add unique constraints to improve the consistency of the models in our RESTful Web Service. We will understand the importance of paginating results and configure and test a global limit/offset pagination scheme with Django REST framework. Then, we will create our own customized pagination class to ensure that requests won't be able to require a huge number of elements on a single page. We will configure filter backend classes and incorporate code into the models to add filtering, searching, and ordering capabilities to the class-based views. We will create a customized filter and make requests to filter, search, and order results. Finally, we will use the browsable API to test pagination, filtering, and ordering. Chapter 8, Securing the API with Authentication and Permissions, presents the differences between authentication and permissions in Django, Django REST framework, and RESTful Web Services. We will analyze the authentication classes included in Django REST framework out of the box. We will follow the steps needed to provide security- and permissions- related data to models. We will work with object-level permissions via customized permission classes and save information about users who make requests. We will configure permission policies and compose and send authenticated requests to understand how the permission policies work. We will use command-line tools and GUI tools to compose and send authenticated requests. We will browse the secure RESTful Web Service with the browsable API feature and work with a simple token-based authentication provided by Django REST framework to understand another way of authenticating requests. Chapter 9, Applying Throttling Rules and Versioning Management, focuses
  • 12. on the importance of throttling rules and how we can combine them with authentication and permissions in Django, Django REST framework, and RESTful Web Services. We will analyze the throttling classes included in Django REST framework out of the box. We will follow the necessary steps to configure many throttling policies in Django REST framework. We will work with global and scope-related settings. Then, we will use command-line tools to compose and send many requests to test how the throttling rules work. We will understand versioning classes and we will configure a URL path versioning scheme to allow us to work with two versions of our RESTful Web Service. We will use command-line tools and the Browsable API to understand the differences between the two versions. Chapter 10, Automating Tests, shows how to automate tests for our RESTful Web Services developed with Django and Django REST framework. We will use different packages, tools, and configurations to perform tests. We will write the first round of unit tests for our RESTful Web Service, run them, and measure tests code coverage. Then, we will analyze tests code coverage reports and write new unit tests to improve the test code coverage. We will understand the new tests code coverage reports and learn the benefits of a good test code coverage. Appendix, Solutions, the right answers for the Test Your Knowledge sections of each chapter are included in the appendix.
  • 13. To get the most out of this book Any computer or device capable of running Python 3.6.3 or greater in Linux, macOS, or Windows. Any computer or device capable of running a modern web browser compatible with HTML 5 and CSS 3 to work with the Browsable API feature included in Django REST framework.
  • 14. Download the example code files You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.p acktpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps: 1. Log in or register at www.packtpub.com. 2. Select the SUPPORT tab. 3. Click on Code Downloads & Errata. 4. Enter the name of the book in the Search box and follow the onscreen instructions. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of: WinRAR/7-Zip for Windows Zipeg/iZip/UnRarX for Mac 7-Zip/PeaZip for Linux The code bundle for the book is also hosted on GitHub at https://github.com/ PacktPublishing/Django-RESTful-Web-Services. We also have other code bundles from our rich catalog of books and videos available at https://github.com/Pac ktPublishing/. Check them out!
  • 15. Download the color images We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://w ww.packtpub.com/sites/default/files/downloads/DjangoRESTfulWebServices_ColorImages. pdf.
  • 16. Conventions used There are a number of text conventions used throughout this book. CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm- 10*.dmg disk image file as another disk in your system." A block of code is set as follows: from django.shortcuts import render # Create your views here. When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: from django.conf.urls import url, include urlpatterns = [ url(r'^', include('drones.urls')), url(r'^api-auth/', include('rest_framework.urls')) ] Any command-line input or output is written as follows: http :8000/toys/ curl -iX GET localhost:8000/toys/3
  • 17. Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel." Warnings or important notes appear like this. Tips and tricks appear like this.
  • 18. Get in touch Feedback from our readers is always welcome. General feedback: Email feedback@packtpub.com and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at questions@packtpub.com. Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com /submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details. Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packtpub.com with a link to the material. If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
  • 19. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about Packt, please visit : packtpub.com.
  • 20. 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
  • 21. 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
  • 22. 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/de v/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.p ython.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
  • 23. 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 HillarDjangoREST01 folder within our user profile folder. For example, if our user profile folder is C:Usersgaston, the virtual environment will be created within C:UsersgastonHillarDjangoREST01. You can replace the specified path with your desired path in each command: %USERPROFILE%HillarDjangoREST01 In Windows PowerShell, the previous path would be as follows: $env:userprofileHillarDjangoREST01 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:
  • 24. python3 -m venv ~/HillarDjangoREST/01 In Windows, in Command Prompt, execute the following command to create a virtual environment: python -m venv %USERPROFILE%HillarDjangoREST01 If you want to work with Windows PowerShell, execute the following command to create a virtual environment: python -m venv $env:userprofileHillarDjangoREST01 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.
  • 25. 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, Libsite- 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:
  • 26. 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 Libsite-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.
  • 27. 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:
  • 28. 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:
  • 29. %USERPROFILE%HillarDjangoREST01Scriptsactivate.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:Usersgaston to (01) C:Usersgaston 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 HillarDjangoREST01ScriptsActivate.ps1 If you receive an error similar to the following lines, it means that you don't have scripts execution enabled: C:UsersgastonHillarDjangoREST01ScriptsActivate.ps1 : File C:UsersgastonHillarDjangoRE http://go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + C:UsersgastonHillarDjangoREST01ScriptsActivate.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess
  • 30. 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:
  • 31. 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%HillarDjangoREST01Scriptsdeactivate.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:userprofileHillarDjangoREST01ScriptsDeactivate.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.
  • 32. 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:
  • 33. 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.
  • 34. 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%HillarDjangoREST01 If you prefer Windows PowerShell, run the following command in Windows PowerShell: cd /d $env:USERPROFILEHillarDjangoREST01 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:
  • 35. python Scriptsdjango-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:
  • 37. 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 (restful01toys 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
  • 38. 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:
  • 39. '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.
  • 40. 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.
  • 41. 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://cyg win.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: h ttps://curl.haxx.se/download.html. Make sure you download the version that includes SSL and SSH.
  • 42. 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:
  • 43. 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, Successfully installed Pygments-2.2.0 certifi-2017.7.27.1 chardet-3.0.4 colorama-0.3.9 httpie-
  • 44. 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:
  • 45. 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:
  • 47. 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:
  • 48. 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/st ore/apps/details?id=air.http.request&hl=en. The following screenshot shows the UI for the iCurlHTTP app running on an iPad Pro:
  • 49. 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.
  • 50. 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
  • 51. 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.
  • 52. 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.
  • 53. Working with Models, Migrations, Serialization, and Deserialization In this chapter, we will define the requirements for our first RESTful Web Service. We will start working with Django, Django REST framework, Python, configurations, models, migrations, serialization, and deserialization. We will create a RESTful Web Service that performs CRUD (short for Create, Read, Update and Delete) operations on a simple SQLite database. We will be: Defining the requirements for our first RESTful Web Service Creating our first model Running our initial migration Understanding migrations Analyzing the database Understanding Django tables Controlling, serialization, and deserialization Working with the Django shell and diving deeply into serialization and deserialization
  • 54. Defining the requirements for our first RESTful Web Service Imagine a team of developers working on a mobile app for iOS and Android and requires a RESTful Web Service to perform CRUD operations with toys. We definitely don't want to use a mock web service and we don't want to spend time choosing and configuring an ORM (short for Object-Relational Mapping). We want to quickly build a RESTful Web Service and have it ready as soon as possible to start interacting with it in the mobile app. We really want the toys to persist in a database but we don't need it to be production-ready. Therefore, we can use the simplest possible relational database, as long as we don't have to spend time performing complex installations or configurations. Django REST framework, also known as DRF, will allow us to easily accomplish this task and start making HTTP requests to the first version of our RESTful Web Service. In this case, we will work with a very simple SQLite database, the default database for a new Django REST framework project. First, we must specify the requirements for our main resource: a toy. We need the following attributes or fields for a toy entity: An integer identifier A name An optional description A toy category description, such as action figures, dolls, or
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 57. back
  • 58. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com