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

Arrow left icon
Profile Icon Gaston C. Hillar
Arrow right icon
€18.99 per month
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3 (3 Ratings)
Paperback Dec 2018 500 pages 2nd Edition
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Gaston C. Hillar
Arrow right icon
€18.99 per month
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3 (3 Ratings)
Paperback Dec 2018 500 pages 2nd Edition
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

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

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 : 9781789532227
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

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

Product Details

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

Packt Subscriptions

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

Frequently bought together


Stars icon
Total 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

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

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

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

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

What are credits? Chevron down icon Chevron up icon

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

What is Early Access? Chevron down icon Chevron up icon

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