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

Hands-On RESTful Python Web Services: Develop RESTful web services or APIs with modern Python 3.7 , Second Edition

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Hands-On RESTful Python Web Services

Working with Models, SQLAlchemy, and Hyperlinked APIs in Flask

In this chapter, we will expand the capabilities of the RESTful API that we started in the previous chapter. We will use SQLAlchemy as our ORM to work with a PostgreSQL database, and we will take advantage of advanced features included in Flask and Flask-RESTful that will allow us to easily organize code for complex APIs, such as models and blueprints.

We will go through the following topics in this chapter:

  • Design a RESTful API to interact with a PostgreSQL 10.5 database
  • Understand the tasks performed by each HTTP method
  • Install packages with the requirements.txt file to simplify our common tasks
  • Create the database
  • Configure the database
  • Write code for the models with their relationships
  • Use schemas to validate, serialize, and deserialize models
  • Combine blueprints with resourceful routing
  • Understand and configure...

Designing a RESTful API to interact with a PostgreSQL 10.5 database

So far, our RESTful API has performed CRUD operations on a simple in-memory dictionary that acted as a data repository. The dictionary is never persisted and, therefore, the data is lost whenever we restart our Flask development server.

Now, we want to create a more complex RESTful API with Flask RESTful to interact with a database model that allows us to work with notifications that are grouped into notification categories. In our previous RESTful API, we used a string attribute to specify the notification category for a notification. In this case, we want to be able to easily retrieve all the notifications that belong to a specific notification category and, therefore, we will have a relationship between a notification and a notification category.

We must be able to perform CRUD operations on different related...

Understanding the tasks performed by each HTTP method

The following table shows the HTTP verbs, the scope, and the semantics for the methods that our new API must support. Each method is composed by an HTTP verb and a scope, and all the methods have well-defined meanings for all the resources and collections:

HTTP verb

Scope

Semantics

GET

Collection of notification categories

Retrieve all the stored notification categories in the collection, sorted by their name in ascending order. Each notification category must include the full URL for the resource. In addition, each notification category must include a list containing all the details of the notifications that belong to the category. The notifications don't have to include the notification category in order to avoid repeating data.

GET

Notification category

Retrieve a single notification category...

Installing packages with the requirements.txt file to simplify our common tasks

Make sure you quit Flask's development server. You just need to press Ctrl + C in the Terminal or Command Prompt window in which it is running.

Now, we will install a number of additional packages. Make sure you have activated the virtual environment we created in the previous chapter and named Flask01. After you activate the virtual environment, it is time to run numerous commands, which will be the same for either macOS, Linux, or Windows.

Now, we will edit the existing requirements.txt file to specify the additional set of packages that our application requires to be installed in any supported platform. This way, it will be extremely easy to repeat the installation of the specified packages with their versions in any new virtual environment.

Use your favorite editor to edit the existing text...

Creating the database

Now, we will create the PostgreSQL 10.5 database that we will use as a repository for our API. You will have to download and install a PostgreSQL database server if you aren't already running it in your computer or on a development server. You can download and install this database management system from its web page (http://www.postgresql.org). If you are working with macOS, Postgres.app provides a really easy way to install and use PostgreSQL on this operating system. You can refer to it from http://postgresapp.com. If you are working with Windows, EnterpriseDB and BigSQL provide graphics installers that simplify the configuration process on modern Windows server or desktop versions (visit https://www.postgresql.org/download/windows for more information).

Notice that the examples have been tested with PostgreSQL 10.5 on macOS, Linux, and Windows.

...

Configuring the database

If you are using the same virtual environment we have created for the previous example, or you downloaded the code sample, the service folder already exists. If you created a new virtual environment, create a folder named service within the root folder for the  virtual environment created.

Create a new config.py file within the service folder. The following lines show the code that declares variables that determine the configuration for Flask and SQLAlchemy. The SQL_ALCHEMY_DATABASE_URI variable generates an SQLAlchemy URI for the PostgreSQL database. Make sure you specify the desired database name in the value for DB_NAME and that you configure the user, password, host, and port based on your PostgreSQL configuration. If you followed the previous steps, use the settings specified in these steps. The code file for the sample is included in the restful_python_2_02_01...

Creating models with their relationships

Now, we will create the models that we will use to represent and persist the notification categories, notifications, and their relationships in the PostgreSQL database.

Open the service/models.py file and replace its contents with the following code. The lines that declare fields related to other models are highlighted in the code listing. If you created a new virtual environment, create a new models.py file within the service folder. The code file for the sample is included in the restful_python_2_02_01 folder, in the Flask01/service/models.py file:

from marshmallow import Schema, fields, pre_load 
from marshmallow import validate 
from flask_sqlalchemy import SQLAlchemy 
from flask_marshmallow import Marshmallow 
 
 
orm = SQLAlchemy() 
ma = Marshmallow() 
 
 
class ResourceAddUpdateDelete():    
    def add(self, resource): 
       ...

Creating schemas to validate, serialize, and deserialize models

Now, we will create the Flask-Marshmallow schemas that we will use to validate, serialize, and deserialize the previously declared NotificationCategory and Notification models, and their relationships.

Open the models.py file within the service folder and add the following code after the last line. The lines that declare fields related to other schemas are highlighted in the code listing. The code file for the sample is included in the restful_python_2_02_01 folder, in the Flask01/service/models.py file:

class NotificationCategorySchema(ma.Schema): 
    id = fields.Integer(dump_only=True) 
    # Minimum length = 3 characters 
    name = fields.String(required=True,  
        validate=validate.Length(3)) 
    url = ma.URLFor('service.notificationcategoryresource',  
        id='<id>',  
 ...

Combining blueprints with resourceful routing

Now, we will create the resources that compose our main building blocks for the RESTful API. First, we will create a few instances that we will use in the different resources. Create a new views.py file within the services folder and add the following lines. Notice that the code imports the HttpStatus enum declared in the http_status.py module that we created in the previous chapter. The code file for the sample is included in the restful_python_2_02_01 folder, in the Flask01/service/views.py file:

from flask import Blueprint, request, jsonify, make_response 
from flask_restful import Api, Resource 
from http_status import HttpStatus 
from models import orm, NotificationCategory, NotificationCategorySchema, Notification, NotificationSchema 
from sqlalchemy.exc import SQLAlchemyError 
 
 
service_blueprint = Blueprint('service...

Understanding and configuring resourceful routing

The following table shows the method of our previously created classes that we want to be executed for each combination of HTTP verb and scope:

HTTP verb

Scope

Class and method

GET

Collection of notifications

NotificationListResource.get

GET

Notification

NotificationResource.get

POST

Collection of notifications

NotificationListResource.post

PATCH

Notification

NotificationResource.patch

DELETE

Notification

NotificationResource.delete

GET

Collection of notification categories

NotificationCategoryListResource.get

GET

Notification category

NotificationCategoryResource.get

POST

Collection of notification categories

NotificationCategoryListResource.post

PATCH

Notification category

NotificationCategoryResource.patch

DELETE

Notification category

NotificationCategoryResource...

Designing a RESTful API to interact with a PostgreSQL 10.5 database


So far, our RESTful API has performed CRUD operations on a simple in-memory dictionary that acted as a data repository. The dictionary is never persisted and, therefore, the data is lost whenever we restart our Flask development server.

Now, we want to create a more complex RESTful API with Flask RESTful to interact with a database model that allows us to work with notifications that are grouped into notification categories. In our previous RESTful API, we used a string attribute to specify the notification category for a notification. In this case, we want to be able to easily retrieve all the notifications that belong to a specific notification category and, therefore, we will have a relationship between a notification and a notification category.

We must be able to perform CRUD operations on different related resources and resource collections. The following table enumerates the resources and the class name that we will...

Understanding the tasks performed by each HTTP method


The following table shows the HTTP verbs, the scope, and the semantics for the methods that our new API must support. Each method is composed by an HTTP verb and a scope, and all the methods have well-defined meanings for all the resources and collections:

HTTP verb

Scope

Semantics

GET

Collection of notification categories

Retrieve all the stored notification categories in the collection, sorted by their name in ascending order. Each notification category must include the full URL for the resource. In addition, each notification category must include a list containing all the details of the notifications that belong to the category. The notifications don't have to include the notification category in order to avoid repeating data.

GET

Notification category

Retrieve a single notification category. The notification category must include the same information explained for each category when we retrieve a collection of notification categories.

POST...

Installing packages with the requirements.txt file to simplify our common tasks


Make sure you quit Flask's development server. You just need to press Ctrl + C in the Terminal or Command Prompt window in which it is running.

Now, we will install a number of additional packages. Make sure you have activated the virtual environment we created in the previous chapter and named Flask01. After you activate the virtual environment, it is time to run numerous commands, which will be the same for either macOS, Linux, or Windows.

Now, we will edit the existing requirements.txt file to specify the additional set of packages that our application requires to be installed in any supported platform. This way, it will be extremely easy to repeat the installation of the specified packages with their versions in any new virtual environment.

Use your favorite editor to edit the existing text file named requirements.txt within the root folder for the virtual environment. Add the following lines after the last...

Creating the database


Now, we will create the PostgreSQL 10.5 database that we will use as a repository for our API. You will have to download and install a PostgreSQL database server if you aren't already running it in your computer or on a development server. You can download and install this database management system from its web page (http://www.postgresql.org). If you are working with macOS, Postgres.app provides a really easy way to install and use PostgreSQL on this operating system. You can refer to it from http://postgresapp.com. If you are working with Windows, EnterpriseDB and BigSQL provide graphics installers that simplify the configuration process on modern Windows server or desktop versions (visit https://www.postgresql.org/download/windows for more information).

Notice that the examples have been tested with PostgreSQL 10.5 on macOS, Linux, and Windows.

 

Note

You have to make sure that the PostgreSQL bin folder is included in the PATH environmental variable. You should be able...

Configuring the database


If you are using the same virtual environment we have created for the previous example, or you downloaded the code sample, the service folder already exists. If you created a new virtual environment, create a folder named service within the root folder for the  virtual environment created.

Create a new config.py file within the service folder. The following lines show the code that declares variables that determine the configuration for Flask and SQLAlchemy. The SQL_ALCHEMY_DATABASE_URI variable generates an SQLAlchemy URI for the PostgreSQL database. Make sure you specify the desired database name in the value for DB_NAME and that you configure the user, password, host, and port based on your PostgreSQL configuration. If you followed the previous steps, use the settings specified in these steps. The code file for the sample is included in the restful_python_2_02_01 folder, in the Flask01/service/config.py file:

import os 
 
basedir = os.path.abspath(os.path.dirname...
Left arrow icon Right arrow icon

Key benefits

  • Combine Python with different data sources to build complex RESTful APIs from scratch
  • Configure and fine-tune your APIs using the best tools and techniques available
  • Use command-line and GUI tools to test CRUD operations performed by RESTful Web Services or APIs

Description

Python is the language of choice for millions of developers worldwide that builds great web services in RESTful architecture. This second edition of Hands-On RESTful Python Web Services will cover the best tools you can use to build engaging web services. This book shows you how to develop RESTful APIs using the most popular Python frameworks and all the necessary stacks with Python, combined with related libraries and tools. You’ll learn to incorporate all new features of Python 3.7, Flask 1.0.2, Django 2.1, Tornado 5.1, and also a new framework, Pyramid. As you advance through the chapters, you will get to grips with each of these frameworks to build various web services, and be shown use cases and best practices covering when to use a particular framework. You’ll then successfully develop RESTful APIs with all frameworks and understand how each framework processes HTTP requests and routes URLs. You’ll also discover best practices for validation, serialization, and deserialization. In the concluding chapters, you will take advantage of specific features available in certain frameworks such as integrated ORMs, built-in authorization and authentication, and work with asynchronous code. At the end of each framework, you will write tests for RESTful APIs and improve code coverage. By the end of the book, you will have gained a deep understanding of the stacks needed to build RESTful web services.

Who is this book for?

This book is for web developers who have a working knowledge of Python and would like to build amazing web services by taking advantage of the various frameworks of Python. You should have some knowledge of RESTful APIs.

What you will learn

  • Select the most appropriate framework based on requirements
  • Develop complex RESTful APIs from scratch using Python
  • Use requests handlers, URL patterns, serialization, and validations
  • Add authentication, authorization, and interaction with ORMs and databases
  • Debug, test, and improve RESTful APIs with four frameworks
  • Design RESTful APIs with frameworks and create automated tests

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 26, 2018
Length: 500 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789532784
Languages :
Concepts :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 26, 2018
Length: 500 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789532784
Languages :
Concepts :

Packt Subscriptions

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

Frequently bought together


Stars icon
Total 122.97
Learn Web Development with Python
€43.99
Hands-On Enterprise Application Development with Python
€41.99
Hands-On RESTful Python Web Services
€36.99
Total 122.97 Stars icon
Banner background image

Table of Contents

13 Chapters
Developing RESTful APIs and Microservices with Flask 1.0.2 Chevron down icon Chevron up icon
Working with Models, SQLAlchemy, and Hyperlinked APIs in Flask Chevron down icon Chevron up icon
Improving Our API and Adding Authentication to it with Flask Chevron down icon Chevron up icon
Testing and Deploying an API in a Microservice with Flask Chevron down icon Chevron up icon
Developing RESTful APIs with Django 2.1 Chevron down icon Chevron up icon
Working with Class-Based Views and Hyperlinked APIs in Django 2.1 Chevron down icon Chevron up icon
Improving Our API and Adding Authentication to it with Django Chevron down icon Chevron up icon
Throttling, Filtering, Testing, and Deploying an API with Django 2.1 Chevron down icon Chevron up icon
Developing RESTful APIs with Pyramid 1.10 Chevron down icon Chevron up icon
Developing RESTful APIs with Tornado 5.1.1 Chevron down icon Chevron up icon
Working with Asynchronous Code, Testing, and Deploying an API with Tornado Chevron down icon Chevron up icon
Assessment Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3
(3 Ratings)
5 star 33.3%
4 star 0%
3 star 0%
2 star 0%
1 star 66.7%
Mike Cross Nov 14, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Nicely presented, well structured book with lots of really good information.
Amazon Verified review Amazon
den Jan 27, 2024
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Can't even get FIRST demo to work. What a junk book. ALL kinds of import errors. HORRIBLE! ANYBODY just run 1st demo to get server up and running? DOES NOT work. No error report from author?
Subscriber review Packt
K Wilson Apr 07, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Considering the amount of money this book cost the quality of the printing is pretty poor.The cover looks like its been digitaly printed on the cheapest photo paper by your local fax copier shop and all the pages feel like they're out of a photocopier machine. Really disappointing.They really stand out as substandard when compared to other books Ive bought over the last 30 years. If they last over time I will be astonished, Packt, what you doing ?!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.