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
Conferences
Free Learning
Arrow right icon
Building Serverless Microservices in Python
Building Serverless Microservices in Python

Building Serverless Microservices in Python: A complete guide to building, testing, and deploying microservices using serverless computing on AWS

Arrow left icon
Profile Icon Takashi Freeman
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (5 Ratings)
Paperback Mar 2019 168 pages 1st Edition
eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Takashi Freeman
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (5 Ratings)
Paperback Mar 2019 168 pages 1st Edition
eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €19.99
Paperback
€24.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

Building Serverless Microservices in Python

Securing your serverless microservices

In this section, we will discuss security in detail.

Lambda security

As we discussed earlier, AWS Lambda is the central component in a serverless stack, or the integration connector with your custom code, triggered by events between AWS managed services. A Lambda function always has an execution IAM role associated with it, and using policies attached to that role is one of the best, and most secure, ways to deny or grant it access to other AWS resources. The beauty is that there is no need to manage or exchange any keys or passwords for a lot of the AWS managed services, such as S3, DynamoDB, and Kinesis Stream. There are some exceptions, such as some of the Amazon Relational Database Service...

Building a serverless microservice data API

In this section, we will look at the architecture and requirements of building a serverless microservice. The rest of the chapter is heavily hands-on in terms of configuration in the AWS Management Console, but also Python code. The Python code follows basic design patterns and is kept simple, so that you can understand and easily adapt it for your own use cases.

Serverless microservice data API requirements

We want to create a microservice that is able to serve a web visits count, for a specific event, of the total users browsing your website.

Setting up Lambda security in the AWS Management Console

We will be signing into the AWS Management Console. The reason we are using the Management Console first is to give you a better understanding of how Lambda functions work, and how they integrate with the other AWS services, such as API Gateway and DynamoDB. In later chapters, we will show you how to deploy Lambda functions using the AWS CLI. If you are a first-timer to Lambda, then I always find it useful to first create a full serverless stack manually in the Management Console to gain a better and deeper understanding than, say, have a magic command spin up the full AWS infrastructure!

We are going to first use the AWS Management Console to create the Lambda IAM role and policies, so that the Lambda function can access DynamoDB, and also write any logs or any statuses to CloudWatch. The Management Console, which we used...

Creating and writing to a NoSQL database called DynamoDB using AWS

We are going to look at creating a DynamoDB table, writing data to the table from hardcoded values, writing data records from a file, and then we are going to show two different ways to query a table:

Creating a DynamoDB in AWS

The following steps show how to create a DynamoDB:

  1. You need to sign in to the AWS Management Console first and then open the AWS DynamoDB console at https://console.aws.amazon.com/dynamodb/.
  2. Choose Create table or, in the DynamoDB navigation pane, choose Tables and choose Create table.
  3. In the Create DynamoDB Table window, perform the following steps:
    1. Under Table name, type user-visits
    2. In Primary key for Partition key, type EventId and...

Creating and writing to a NoSQL database called DynamoDB using Python

Now that we understand how to create a table, add data, and query DynamoDB using the AWS Console, we will look at how we can do this using only Python code.

We recommend you use a Python Integrated development environment (IDE) such as Eclipse PyDev (http://www.pydev.org/download.html) or PyCharm (https://www.jetbrains.com/pycharm/). You do not need to use an IDE, but I would recommend that you do. If you really want to, you can use VI, for example, on Linux to actually edit your code. But using an IDE allows you, for example, to run debugging or set up unit testing locally and step through it, which makes it easier and more productive for development.

First create the table using Boto3 https://boto3.readthedocs.io/ in Python. Run the code in the following section in PyCharm or your favorite text editor...

Creating a Lambda to query DynamoDB

Now that we have the security and user-visits table set up with some data, and know how to write code to query that DynamoDB table, we will write the Lambda Python code.

Creating the Lambda function

Now we have the IAM role with two IAM policies attached, create the Lambda function itself. Here, we are creating a function from scratch, as we want to walk through the full details to deepen your understanding of what is involved in creating a serverless stack. The following diagram shows data API architecture involving CloudWatch, DynamoDB, IAM, and Lambda:

Perform the following steps:

  1. Sign in to the AWS Management Console and open the AWS Lambda console at https://console.aws.amazon.com/lambda/...

Setting up the API Gateway and integrating it with a Lambda proxy

Now that we know the Lambda function works with some API Gateway test data, and returns a header and body with a statusCode of 200, we just need to add the API Gateway that will invoke the Lambda function, as shown in the following diagram:

Perform the following steps:

  1. Sign in to the AWS Management Console and open the API Gateway console at https://console.aws.amazon.com/apigateway/.
  2. Choose Get Started or, in the Amazon API Gateway navigation pane, choose APIs and choose Create API.
  3. On the Create page, perform the following steps:
    1. In Choose Protocol, select REST
    2. In Create new API, select New API
    3. Under Settings, type metrics for API name
    4. Choose Regional for Endpoint Type
    5. Choose Create API
  4. Choose Create Resource from the Actions drop-down menu.
  5. In the New Child Resource window, perform the following steps...

Connecting API Gateway, Lambda, and DynamoDB

Now that we know the API Gateway integration with the Lambda function works, we will deploy it and get the URL. The architecture is shown in the following diagram:

The workings of this architecture is as follows:

  1. Sign in to the AWS Management Console and open the API Gateway console at https://console.aws.amazon.com/apigateway/.
  2. In the Amazon API Gateway navigation pane, choose APIs and metrics.
  3. Select Resources under metrics and /Vists/{resourceId}, and choose Deploy API from the Actions drop-down menu.
  4. In the Deploy API pop-up window, perform the following steps:
    1. In Deployment stage, choose [New Stage]
    2. In Stage name, type prod
    3. In Stage description, type prod
    4. Select Deploy
  5. The Stages under metrics should be automatically selected on the left-hand menu.
  6. Select GET under prod/visits/{resourceId}/GET to get the invoke URL. The invoke...

Cleaning-up

You will need to delete the resources manually. I recommend you use the AWS Console to do so. Perform the following steps:

  1. Deleting API Gateway:
    1. Log on to the Console at https://console.aws.amazon.com/apigateway/
    2. Choose Resource under metrics on the left-hand APIs menu
    3. Choose Delete API from the Actions drop-down menu
    4. Type metrics in the Enter the name of the API before confirming this action textbox
    5. Choose Delete API
  2. Deleting the DynamoDB table:
    1. Log on to the Console at https://console.aws.amazon.com/dynamodb/
    2. Choose Tables on the left-hand DynamoDB menu
    3. Choose user-visits
    4. Choose Delete table
    5. Choose Delete
  1. Deleting the Lambda function:
    1. Log on to the Console at https://console.aws.amazon.com/lambda/
    2. Choose Functions on the left-hand AWS Lambda menu
    3. Choose lambda-dynamo-data-api
    4. Choose Delete function under the Actions menu
    5. Choose Delete
  2. Deleting...

Summary

In this chapter, we have discussed security and why it is important. Applying the OWASP security by design principles is a good first step to ensure that your serverless stack is secure. We then discussed IAM roles and gave an overview of policies, explaining how they are the key documents to ensure restricted access to AWS resources. We then looked at an overview of some of the security concepts and principles regarding securing your serverless microservices, specifically regarding Lambda, API Gateway, and DynamoDB.

We then built a scalable serverless microservice with a RESTful data API. We started by creating a DynamoDB table, then added data to it, and queried it, first using the AWS console manually, then using the Python Boto3 SDK. We then built a simple Lambda to parse the request URL parameters, query DynamoDB, and return the records as part of a response body....

Setting up Lambda security in the AWS Management Console


We will be signing into the AWS Management Console. The reason we are using the Management Console first is to give you a better understanding of how Lambda functions work, and how they integrate with the other AWS services, such as API Gateway and DynamoDB. In later chapters, we will show you how to deploy Lambda functions using the AWS CLI. If you are a first-timer to Lambda, then I always find it useful to first create a full serverless stack manually in the Management Console to gain a better and deeper understanding than, say, have a magic command spin up the full AWS infrastructure!

We are going to first use the AWS Management Console to create the Lambda IAM role and policies, so that the Lambda function can access DynamoDB, and also write any logs or any statuses to CloudWatch. The Management Console, which we used earlier, in Chapter 1, Serverless Microservices Architectures and Patterns, allows you to centrally control all...

Creating and writing to a NoSQL database called DynamoDB using AWS


We are going to look at creating a DynamoDB table, writing data to the table from hardcoded values, writing data records from a file, and then we are going to show two different ways to query a table:

Creating a DynamoDB in AWS

The following steps show how to create a DynamoDB:

  1. You need to sign in to the AWS Management Console first and then open the AWS DynamoDB console at https://console.aws.amazon.com/dynamodb/.
  2. Choose Create table or, in the DynamoDB navigation pane, choose Tables and choose Create table.
  3. In the Create DynamoDB Table window, perform the following steps:
    1. Under Table name, type user-visits
    2. In Primary key for Partition key, type EventId and choose String
    3. Check the Add sort key box
    4. In Sort Key, type EventDay and choose Number

The partition key and hash key can be used interchangeably, like sort key and range keys. A primary key can be the partition key alone, or a composite key with both a partition key and a sort...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create a secure, cost-effective, and scalable serverless data API
  • Use identity management and authentication for a user-specific and secure web application
  • Go beyond traditional web hosting to explore the full range of cloud hosting options

Description

Over the last few years, there has been a massive shift from monolithic architecture to microservices, thanks to their small and independent deployments that allow increased flexibility and agile delivery. Traditionally, virtual machines and containers were the principal mediums for deploying microservices, but they involved a lot of operational effort, configuration, and maintenance. More recently, serverless computing has gained popularity due to its built-in autoscaling abilities, reduced operational costs, and increased productivity. Building Serverless Microservices in Python begins by introducing you to serverless microservice structures. You will then learn how to create your first serverless data API and test your microservice. Moving on, you'll delve into data management and work with serverless patterns. Finally, the book introduces you to the importance of securing microservices. By the end of the book, you will have gained the skills you need to combine microservices with serverless computing, making their deployment much easier thanks to the cloud provider managing the servers and capacity planning.

Who is this book for?

If you are a developer with basic knowledge of Python and want to learn how to build, test, deploy, and secure microservices, then this book is for you. No prior knowledge of building microservices is required.

What you will learn

  • Discover what microservices offer above and beyond other architectures
  • Create a serverless application with AWS
  • Gain secure access to data and resources
  • Run tests on your configuration and code
  • Create a highly available serverless microservice data API
  • Build, deploy, and run your serverless configuration and code

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 29, 2019
Length: 168 pages
Edition : 1st
Language : English
ISBN-13 : 9781789535297
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 : Mar 29, 2019
Length: 168 pages
Edition : 1st
Language : English
ISBN-13 : 9781789535297
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 99.97
Python Microservices Development
€41.99
Hands-On Docker for Microservices with Python
€32.99
Building Serverless Microservices in Python
€24.99
Total 99.97 Stars icon
Banner background image

Table of Contents

7 Chapters
Serverless Microservices Architectures and Patterns Chevron down icon Chevron up icon
Creating Your First Serverless Data API Chevron down icon Chevron up icon
Deploying Your Serverless Stack Chevron down icon Chevron up icon
Testing Your Serverless Microservice Chevron down icon Chevron up icon
Securing Your Microservice Chevron down icon Chevron up icon
Summary and Future Work 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 Full star icon Empty star icon Empty star icon 3
(5 Ratings)
5 star 20%
4 star 20%
3 star 20%
2 star 20%
1 star 20%
User Sep 16, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Found this is a really good book to get me up and running with Serverless in AWS using Python, wish it were bit longer. Really like how the author introduces microservice architecture theory, with practical examples I can use and the in-depth and hands-on section on many forms of testing.
Amazon Verified review Amazon
Amazon Customer May 06, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
best for aws users trying to learn python scripting
Amazon Verified review Amazon
Andres G. T. Jul 25, 2020
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
It has a good intro to microservices concepts and good practice with lambda. However, if you plan to follow the exercises you may find it difficult. For example, sometimes the code it's repetitive and the author doesn't explain why, or he doesn't tell you that, after writing some python scripts, you have to run them locally first before running a test for a lambda function in AWS. Also, the GitHub site for the book is hard to find the code for the corresponding section in the book (at the least in the Kindle edition).
Amazon Verified review Amazon
Rob Shearer Apr 08, 2021
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
This can't really be called a "book". It's a tutorial, where you follow the directions given to create an AWS serverless service. There is a brief description of what each command does, but very little discussion of why or what other approaches are possible. Many of the steps are literally "cut and paste this code into the box".The real issue is that even as a tutorial it's atrocious. The quality of the code itself wouldn't pass muster in any serious programming team. There seems to be no rhyme or reason to what is abstracted or parameterized, leading to code that is overcomplicated and verbose while providing no real value for reuse. But it's also terribly written for a tutorial. When code from one step is expanded with a little bit of additional functionality in the next step, that isn't added as a few extra lines of code; instead the entire code is arbitrarily rewritten with slightly different function names for no obvious reason. There was clearly no intention of readers ever actually "working through" the tutorial by coding it up themselves (and experimenting with variations), only cutting and pasting.I wish I had the knowledge to comment on whether the tutorial genuinely offers modern best practice for developing serverless applications. I don't. But the author's obvious lack of any production software engineering expertise or experience does not inspire confidence.That this "book" was pushed out the door in this state must be taken as a reflection of its publisher. Based on this book, I will make sure not to waste money on any other Packt releases in the future.
Amazon Verified review Amazon
utente Sep 09, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Terribile. È scritto coi piedi. Sembra il risultato di una persona a cui è stato detto che dovrebbe scrivere un libro, e ha buttato giù quattro appunti. Termini usati senza definirli, o con la definizione dopo il primo utilizzo. Frasi senza capo ne coda. Mi sono fermato quando ho visto una immagine in bianco e nero con la spiegazione: "I rettangoli in verde indicano i servizi...". QUesto genere di libri distruggono la fiducia in un autore e in una casa editrice. Non li conoscevo prima, li eviterò in seguito. Mi spiace perchè l'argomento mi interessava davvero :-(
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.