Hands-On RESTful Python Web Services
eBook - ePub

Hands-On RESTful Python Web Services

Develop RESTful web services or APIs with modern Python 3.7, 2nd Edition

Gaston C. Hillar

Compartir libro
  1. 500 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Hands-On RESTful Python Web Services

Develop RESTful web services or APIs with modern Python 3.7, 2nd Edition

Gaston C. Hillar

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Explore the best tools and techniques to create lightweight, maintainable, and scalable Python web services

Key Features

  • 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

Book 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.

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

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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Hands-On RESTful Python Web Services un PDF/ePUB en línea?
Sí, puedes acceder a Hands-On RESTful Python Web Services de Gaston C. Hillar en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in Python. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781789532784
Edición
2

Developing RESTful APIs and Microservices with Flask 1.0.2

In this chapter, we will start our journey toward RESTful Web APIs with Python 3.7 and four different web frameworks. Python is one of the most popular and versatile programming languages. There are thousands of Python packages, and these allow you to extend Python capabilities to any kind of domain you can imagine, such as web development, Internet of Things (IoT), artificial intelligence, machine learning, and scientific computing. We can work with many different web frameworks and packages to easily build simple and complex RESTful Web APIs with Python, and we can combine these frameworks with other Python packages.
We can leverage our existing knowledge of Python and all of its packages to code the different pieces of our RESTful Web APIs and their ecosystem. We can use the object-oriented features to create code that is easier to maintain, understand, and reuse. We can use all the packages that we are already comfortable with to interact with databases, web services, and different APIs. Python makes it easy for us to create RESTful Web APIs. In addition, lightweight frameworks, such as Flask, are ideal candidates for creating microservices that provide RESTful APIs. We don't need to learn another programming language; we can use the one we already know and love.
In this chapter, we will start working with Flask 1.0.2 and its Flask-RESTful extension, and we will create a RESTful Web API that performs CRUD (short for Create, Read, Update, and Delete) operations on a simple list. We will establish the baseline to develop microservices that provide a RESTful API with Flask. We will look at the following topics:
  • Design a RESTful API that performs CRUD operations in Flask with the Flask-RESTful extension
  • Understand the tasks performed by each HTTP method
  • Understand microservices
  • Work with lightweight virtual environments
  • Set up the virtual environment with Flask and its Flask-RESTful extension
  • Declare status codes for the responses with an enumerable
  • Create the model
  • Use a dictionary as a repository
  • Configure output fields
  • Work with resourceful routing on top of Flask pluggable views
  • Configure resource routing and endpoints
  • Make HTTP requests to the Flask API
  • Work with command-line tools to interact with the Flask API
  • Work with GUI tools to interact with the Flask API
  • Consume the API with other programming languages

Designing a RESTful API to interact with a simple data source

Imagine that we have to configure the notification messages to be displayed in an OLED (short for Organic Light Emitting Diode) display wired to an IoT device. The IoT device is capable of running Python 3.7.1, Flask 1.0.2, and other Python packages. There is a team writing code that retrieves string messages that represent notifications from a dictionary and displays them in the OLED display wired to the IoT device. We have to start working on a mobile app and a website that has to interact with a RESTful API to perform CRUD operations with string messages that represent notifications.
We don't need an ORM (short for Object-Relational Mapping) because we won't persist the notifications on a database. We will just work with an in-memory dictionary as our data source. It is one of the requirements we have for this RESTful API. In this case, the RESTful Web Service will be running on the IoT device; that is, we will run the Flask development service on the IoT device.
We will definitely lose scalability for our RESTful API because we have the in-memory data source in the service, and therefore we cannot run the RESTful API in another IoT device. However, we will work with another example that is related to a more complex data source that will be able to scale in the RESTful way later. The first example is going to allow us to understand how Flask and Flask-RESTful work together with a very simple in-memory data source.
We have chosen Flask because it is an extremely lightweight framework, we don't need to configure an ORM, and we want to start running the RESTful API on the IoT device as soon as possible to allow all the teams to interact with it. We consider that there will be a website that will be coded with Flask too, and therefore, we want to use the same web micro-framework to power the website and the RESTful Web Service. In addition, Flask is an appropriate choice to create a microservice that can run our RESTful API on the cloud.
There are many extensions available for Flask that make it easier to perform specific tasks with the Flask micro-framework. We will take advantage of Flask-RESTful, an extension that will allow us to encourage best practices while building our RESTful API. In this case, we will work with a Python dictionary as the data source. As previously explained, we will work with more complex data sources in forthcoming examples.
First, we must specify the requirements for our main resource—a notification. We need the following attributes or fields for a notification:
  • An integer identifier.
  • A string message.
  • A TTL (short for Time to Live), that is, a duration in seconds that will indicate the time the notification message has to be displayed on the OLED display.
  • A creation date and time. The timestamp will be added automatically when adding a new notification to the collection.
  • A notification category description, such as Warning or Information.
  • An integer counter that indicates the times when the notification message has been displayed on the OLED display.
  • A Boolean value that indicates whether the notification message was displayed at least once on the OLED display.
The following table shows the HTTP verbs, the scope, and the semantics for the methods that our first version of the API must support. Each method is composed of an HTTP verb and a scope, and all the methods have a well-defined meaning for all notifications and collections. In our API, each notification has its own unique URL:
HTTP verb
Scope
Semantics
GET
Collection of notifications
Retrieve all the stored notifications in the collection.
GET
Notification
Retrieve a single notification.
POST
Collection of notifications
Create a new notification in the collection.
PATCH
Notification
Update one or more fields for an existing notification.
DELETE
Notification
Delete an existing notification.

Understanding the tasks performed by each HTTP method

Let's consider that http://localhost:5000/service/notifications/ is the URL for the collection of notifications. If we add a number to the previous URL, we identify a specific notification whose ID is equal to the specified numeric value. For example, http://localhost:5000/service/notifications/5 identifies the notification whose ID is equal to 5.
We want our API to differentiate collections from a single resource of the collection in the URLs. When we refer to a collection, we will use a slash (/) as the last character for the URL, as in http://localhost:5000/service/notifications/. When we refer to a single resource of the collection, we won't use a slash (/) as the last character for the URL, as in http://localhost:5000/service/notifications/5.
We have to compose and send an HTTP request with the following HTTP verb (POST) and request URL (http://localhost:5000/service/notifications/) to create a new notification. In addition, we have to provide the JSON key-value pairs with the field names and the values to create the new notification. As a result of the request, the service will validate the values provided for the fields, making sure that it is a valid notification and persists it in the in-memory notifications dictionary. The service will return a 201 Created status code and a JSON body with the recently added notification serialized to JSON, including the assigned ID that was automatically generated by the service to the notification object:
POST http://localhost:5000/service/notifications/ 
We have to compose and send an HTTP request with the following HTTP verb (GET) and request URL (http://localhost:5000/service/notifications/{id}) to retrieve the notification whose ID matches the specified numeric value in the place where {id} is written. For example, if we use the http://localhost:5000/service/notifications/23 request URL, the service will retrieve the notification whose ID matches 23 from the dictionary. If a notification is found, the service will serialize the notification object into JSON and return a 200 OK status code and a JSON body with the serialized notification object. If no notification matches the specified ID or primary key, the service will return just a 404 Not Found status:
GET http://localhost:5000/service/notifications/{id} 
We have to compose and send an HTTP request with the following HTTP verb (PATCH) and request URL (http://localhost:5000/service/notifications/{id}) to update one or more fields for the notification whose ID matches the specified numeric value in the place where {id} is written. In addition, we have to provide the JSON key-value pairs with the field names to be updated and their new values. As a result of the request, the service will validate the values provided for the fields, update these fields on the notification that matches the specified ID, and update the notification in the dictionary if it is a valid notification. The service will return a 200 OK status code and a JSON body with the recently updated notification serialized to JSON. If we provide invalid data for the fields to be updated, the service will ret...

Índice