Book Image

Hands-On RESTful Python Web Services - Second Edition

By : Gaston C. Hillar
1 (1)
Book Image

Hands-On RESTful Python Web Services - Second Edition

1 (1)
By: Gaston C. Hillar

Overview of this book

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.
Table of Contents (19 chapters)
Title Page
Dedication
About Packt
Contributors
Preface
Index

Preface

REST (short for REpresentational State Transfer) is the architectural style that is driving modern web development and mobile app development. In fact, developing and interacting with RESTful web services is a required skill in any modern software development job. Sometimes, you have to interact with an existing API and in other cases, you have to design a RESTful API from scratch and make it work with JSON (short for JavaScript Object Notation).

Python is one of the most popular programming languages. Python 3.6 and 3.7 are the most modern versions of Python. Python is open source and multiplatform, and you can use it to develop any kind of application, from websites to extremely complex scientific computing applications. There is always a Python package that makes things easier for you to avoid reinventing the wheel and solve the problems faster. The most important and popular cloud computing providers make it easy to work with Python and its related web frameworks. Thus, Python is an ideal choice for developing RESTful web services. This book covers all the things you need to know to select the most appropriate Python web framework and develop a RESTful API from scratch.

You will work with the latest versions of the four most popular Python web frameworks that make it easy to develop RESTful web services: Flask, Django, Pyramid, and Tornado. Each web framework has its advantages and disadvantages. You will work with examples that represent appropriate cases for each of these web frameworks, in combination with additional Python packages that will simplify the most common tasks. You will learn how to use different tools to test and develop high-quality, consistent, and scalable RESTful web services.

You will write unit tests and improve test coverage for the RESTful web services that you will develop throughout the book. You won't just run the sample code; you will also make sure that you write tests for your RESTful API. You will always write modern Python code and you will take advantage of features introduced in the latest Python versions.

This book will allow you to learn how to take advantage of many packages that will simplify the most common tasks related to RESTful web services. You will be able to start creating your own RESTful APIs for any domain in any of the covered web frameworks in Python 3.6, 3.7, or greater.

 

 

Who this book is 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 this book covers

Chapter 1, Developing RESTful APIs and Microservices with Flask 1.0.2, begins working with Flask and its Flask-RESTful extension. We will create a RESTful Web API that performs CRUD (short for Create, Read, Update, and Delete) operations on a simple list.

Chapter 2, Working with Models, SQLAlchemy, and Hyperlinked APIs in Flask, expands 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.

Chapter 3, Improving Our API and Adding Authentication to it with Flask, improves the RESTful API in many ways. We will add user-friendly error messages when resources aren't unique. We will test how to update single or multiple fields with the PATCH method and we will create our own generic pagination class. Then, we will start working with authentication and permissions. We will add a user model and update the database. We will make many changes in the different pieces of code to achieve a specific security goal, and we will take advantage of Flask-HTTPAuth and passlib to use HTTP authentication in our API.

Chapter 4, Testing and Deploying an API in a Microservice with Flask, explains how to set up a testing environment. We will install pytest and the necessary plugins to make it easy to discover and execute unit tests, and we will create a new database to be used for testing. We will write a first round of unit tests, measure test coverage, and then write additional unit tests to improve test coverage. Finally, we will learn many considerations for deployment, scalability, and the execution of a Flask RESTful API within a microservice on the cloud.

Chapter 5, Developing RESTful APIs with Django 2.1, shows how to start working with Django and Django REST Framework, and we will create a RESTful Web API that performs CRUD operations on a simple SQLite database.

 

 

Chapter 6, Working with Class-Based Views and Hyperlinked APIs in Django 2.1, expands the capabilities of the RESTful API that we started in the previous chapter. We will change the ORM settings to work with a more powerful PostgreSQL 10.5 database and we will take advantage of advanced features included in Django REST Framework that allow us to reduce boilerplate code for complex APIs, such as class-based views.

Chapter 7Improving Our API and Adding Authentication to it with Django, improves the RESTful API that we started in the previous chapter. We will add unique constraints to the model and update the database. We will make it easy to update single fields with the PATCH method and we will take advantage of pagination. We will start working with authentication, permissions, and throttling.

Chapter 8, Throttling, Filtering, Testing, and Deploying an API with Django 2.1, takes advantage of many features included in Django REST Framework to define throttling policies. We will use filtering, searching, and ordering classes to make it easy to configure filters, search queries, and the desired order for the results in HTTP requests. We will use the Browsable API feature to test these new features included in our API. We will write a first round of unit tests, run them with pytest, and then write additional unit tests to improve test coverage. Finally, we will learn many considerations for running Django RESTful APIs on the cloud.

Chapter 9, Developing RESTful APIs with Pyramid 1.10, works with Pyramid combined with other useful packages to create a RESTful Web API. We will design a RESTful API to interact with a simple data source. We will define the requirements for our API and we will understand the tasks performed by each HTTP method. We will create the class that represents a surfboard metric and we will use marshmallow to validate, serialize, and deserialize the model. We will write functions to process the different HTTP request methods and we will configure the view handlers.

Chapter 10, Developing RESTful APIs with Tornado 5.1.1, works with Tornado to create a RESTful Web API. We will design a RESTful API to interact with slow sensors and actuators. We will define the requirements for our API and we will understand the tasks performed by each HTTP method. We will create the classes that represent a drone and write code to simulate slow I/O operations that are called for each HTTP request method. We will write classes that represent request handlers and process the different HTTP requests and configure the URL patterns to route URLs to request handlers and their methods.

 

 

Chapter 11, Working with Asynchronous Code, Testing, and Deploying an API with Tornado, explains the difference between synchronous and asynchronous execution. We will create a new version of the RESTful API that takes advantage of the non-blocking features in Tornado combined with asynchronous execution. We will improve scalability for our existing API and we will make it possible to start executing other requests while waiting for the slow I/O operations with sensors and actuators. Then, we will set up a testing environment. We will install pytest to make it easy to discover and execute unit tests. We will write a first round of unit tests, measure test coverage, and then write additional unit tests to improve test coverage.

To get the most out of this book

In order to work with the different samples for Python 3.6 and Python 3.7, you will need a computer with an Intel Core i3 or higher CPU and at least 4GB of RAM. You can work with any of the following operating systems:

  • Windows 7 or greater (Windows 8, Windows 8.1, or Windows 10)
  • Windows Server 2012 or greater (Windows Server 2016 or Windows Server 2019)
  • macOS Mountain Lion or greater
  • Any Linux version capable of running Python 3.7.1 and any modern browser with JavaScript support

You will need Python 3.7.1 or greater installed on your computer.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.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.packt.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/Hands-On-RESTful-Python-Web-Services-Second-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. 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: https://www.packtpub.com/sites/default/files/downloads/9781789532227_ColorImages.pdf.

Conventions used

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

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: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

html, body, #map {
 height: 100%; 
 margin: 0;
 padding: 0
}

 

 

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)

Any command-line input or output is written as follows:

# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample     /etc/asterisk/cdr_mysql.conf

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: "Clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

 

 

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

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.packt.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 [email protected] 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.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

 

 

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 packt.com.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.