COSC2626/COSC2640 Cloud Computing
Exercise 5: AWS Lambda and API Gateway
In this activity you will learn how to build a serverless application using the most prominent
serverless technology around, which is AWS lambda. Such an application provides you the
flexibility to run your code when required rather than having to maintain a running service
available using a dedicated server for it. This is also cost-effective as you only pay for the
computing service when you use it. You don’t need to pay for application idle time.
You can use AWS Lambda to extend other AWS services with custom logic or create your
own back-end services that operate at AWS scale, performance, and security. We encourage
you to visit AWS Lambda online documentation for further information on features, use cases
and how to get started.
Amazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring,
and securing REST and WebSocket APIs at scale. API developers can create APIs that
access AWS or other web services as well as data stored in the AWS Cloud.
API Gateway creates REST APIs that:
• Are HTTP-based.
• Adhere to the REST protocol, which enables stateless client-server communication.
• Implement standard HTTP methods such as GET, POST, PUT, and DELETE. (Find out
more about What is HTTP, and how is it related to REST?)
As an API developer, API Gateway allows you to create APIs for use in your own client
applications (apps). Or you can make your APIs available to third-party app developers.
Together with AWS Lambda, API Gateway forms the app-facing part of the AWS serverless
infrastructure. For an app to call publicly available AWS services, you can use Lambda to
interact with required services and expose Lambda functions through API methods in API
Gateway.
1
AWS Lambda runs your code on a highly available computing infrastructure. It performs the
necessary execution and administration of computing resources. To enable serverless
applications, API Gateway supports streamlined proxy integrations with AWS Lambda and
HTTP endpoints.
Using AWS Lambda with Amazon API Gateway is the easiest way to create microservices.
Here are some examples:
• Event handlers = one function per event type
• Serverless backends = one function per API / path
• Data processing = one function per data type
You can explore more about Amazon API Gateway from AWS online documentation here.
In this exercise, you will learn the basics of running code on AWS Lambda without
provisioning or managing servers. We will walk through how to create a Hello World Lambda
function using the AWS Lambda console. We will then show you how to manually invoke the
Lambda function using sample event data and review your output metrics. We also provide
a full example to show you how to set up endpoints using API Gateway to trigger Lambda
functions which interact with your DynamoDB database. Everything done in this tutorial is
free tier eligible.
Activity 1: Create a HelloWorld serverless function with AWS Lambda
Activity 2: Using AWS Lambda with Amazon S3
Activity 3: Using Lambda Functions with AWS DynamoDB
Activity 4: An online Voting System (Single Page Application)
2
Activity 1: Create a HelloWorld serverless function with AWS Lambda
Step 1: Enter the Lambda Console.
Go to the AWS Academy, start a new lab session. Then, browse the AWS Management
Console attached to your lab session.
Find AWS Lambda under the Compute category either by using the search bar available in
the AWS Management Console or by expanding the Services drop-down box.
Click to go to AWS Lambda Console.
Step 2: From AWS Lambda dashboard, select Create function.
3
Step 3: In the Create function wizard, select Use a blueprint to run a sample Lambda
function provided by AWS.
Blueprints provide example code to do some minimal processing. Most blueprints process
events from specific event sources, such as Amazon S3, Amazon DynamoDB, or a custom
application.
o In the AWS Lambda console, select Create a Function.
Note: The console shows this page only if you do not have any Lambda functions created.
If you have created functions already, you will see the Lambda > Functions page. On the
list page, choose Create a function to go to the Create function page.
o Select Use a blueprint out of the options available to create a function.
o In the Blueprints search box, type in hello world function and select Hello world
function (python3.10).
Step 4: Configure and Create Your Lambda Function.
A Lambda function consists of code you provide, associated dependencies, and configuration.
The configuration information you provide includes the compute resources you want to
allocate (for example, memory), execution timeout, and an IAM role that AWS Lambda can
assume to execute your Lambda function on your behalf.
o You will now enter Basic Information about your Lambda function, such as
4
• Name: You can name your Lambda function here. For this exercise, enter hello-
world-python.
• Role name: AWS Academy provides restricted access to students on creating roles
as well as several other Identity and Access Management related tasks. Therefore,
in this exercise, we will use Use an existing role option and select a role that AWS
Academy already created for us. Select LabRole from the drop-down list.
• Lambda Function Code: In this section, you can review the example code authored in
Python. We will leave the existing implementation as is.
• Handler: You can specify a handler (a method/function in your code) where AWS
Lambda can begin executing your code.
AWS Lambda provides event data as input to this handler, which processes the event.
In this example, Lambda identifies this from the code sample, and this should be pre-
populated with lambda_function.lambda_handler.
o Go to the bottom of the page and select Create function.
o Click on the Configure tab from the AWS Lambda options menu to configure the memory,
timeout, and VPC settings, etc of your lambda function. For this exercise, keep the default
Lambda function configuration values unchanged.
5
Step 5: Invoke Lambda Function and Verify Results.
Now, the AWS Lambda console shows the hello-world-python Lambda function. You can
now test the function, verify results, and review the logs.
o Select Test tab from the AWS Lambda options menu and select Create new event as
the Test event action to create a new test event.
o When you are in the test event creation wizard,
• Type in an Event name: HelloWorldEvent.
• Leave Event sharing settings as Private, which is its default value.
• Choose hello-world from the sample event Template list.
• You can change the values in the sample JSON, but don’t change the event
structure. For this exercise, replace value1 with the phrase “hello, world!”.
o Select Save changes.
o Click Test.
o Upon successful execution, view the results in the console:
• The Execution results section verifies that the execution succeeded.
• The Summary section shows the key information reported in the Log output.
6
• The Log output section will show the logs generated by the Lambda function
execution.
Step 6: Monitor Your Metrics.
AWS Lambda automatically monitors Lambda functions and reports metrics through Amazon
CloudWatch. To help you monitor your code as it executes, Lambda automatically tracks the
number of requests, the latency per request, and the number of requests resulting in an error
and publishes the associated metrics.
o Invoke the Lambda function a few more times by repeatedly clicking the Test button. This
will generate the metrics that can be viewed in the next step.
o Select Monitor tab from the AWS Lambda options menu to view the results.
o Click the Metrics option to view metrics of your Lambda function. Lambda metrics are
reported through Amazon CloudWatch. You can leverage these metrics to set custom
alarms. For more information about CloudWatch, see the Amazon CloudWatch Developer
Guide.
7
The Metrics tab will show seven CloudWatch metrics: Invocations, Duration, Error count and
success rate (%), Throttles, Async delivery failures, IteratorAge and Concurrent executions.
With AWS Lambda, you pay for what you use. After you hit your AWS Lambda free tier limit,
you are charged based on the number of requests for your functions (invocation count) and
the time your code executes (invocation duration). For more information, see AWS Lambda
Pricing.
Step 7: Delete the Lambda Function.
While you will not get charged for keeping your Lambda function, you can easily delete it from
the AWS Lambda console.
o Select the Actions button and click Delete function.
o You will be asked to confirm the deletion of your Lambda function.
8
Activity 2: Using AWS Lambda with Amazon S3
After you have learnt how to write your first few AWS Lambda functions, we will continue
learning how to use AWS Lambda with Amazon S3.
You will learn from this AWS official online tutorial as a preparation step before we take you
through an example of how to build a serverless application using AWS Lambda.
Note: Please skip the steps associated with explicitly creating AWS Identity and Access
Management (IAM) roles and policies.
AWS Academy does not allow users to create IAM resources by design. Where an IAM role
is necessary, use LabRole – the default role provided to you by AWS Academy.
Activity 3: Using Lambda Functions with AWS DynamoDB
In Exercise 4, you learned about AWS DynamoDB. In this task, you will learn how DynamoDB
can trigger AWS Lambda functions when data is added to the tables, updated, or deleted.
Follow this online tutorial on “Using Lambda Function with Amazon DynamoDB” to add items
to the DynamoDB table. AWS Lambda will then read the data and send email with the data
added.
Note: Please skip the steps associated with explicitly creating AWS Identity and Access
Management (IAM) roles and policies.
AWS Academy does not allow users to create IAM resources by design. Where an IAM role
is necessary, use LabRole – the default role provided to you by AWS Academy.
9
Activity 4: An online Voting System (Single Page Application)
AWS S3 + AWS API Gateway + AWS Lambda + Amazon DynamoDB
(Reference: https://medium.com/@manbobo2012/build-a-serverless-web-application-within-
15-mins-on-aws-8f7771a712ca)
Serverless Architecture
A serverless architecture is a way to build and run applications and services without having to
manage infrastructure. In short, we do not have to maintain our server but just focus on coding,
this is the first reason.
Secondly, it is really “pay as you go”. If we use server, some of the time like early morning the
usage is very low. But it does not mean the server cloud be closed because someone may
use, even though the traffic is low. But for serverless architecture, you just pay for the number
of requests. If no one request your system, then no money you have to pay.
Thirdly, you do not need to choose the hardware specification e.g. number of CPU or size of
RAM, you just need to take a look on the traffic and directly adjust the system based on traffic.
Solution Diagram
10
What we have used here are Amazon S3, Amazon API Gateway, AWS Lambda, and Amazon
DynamoDB. The workflow is:
1. User visits our website stored in S3. Note: we use a Single Page Application (SPA)
in this example. In single-page applications, the same page reappears with new
information when the user clicks on the link. It works on re-rendering and the same
page is loaded with dynamic content. There is no new page loaded on any further
request to the server.
2. When user votes, the request will pass through the API Gateway.
3. The Lambda function gets the request and communicate with DynamoDB, it could be
read or write.
4. After read or write, the Lambda function returns a response string to API Gateway.
5. The result is reflected on the front-end page, so customer could see the change
immediately.
Before we start, please download the prepared files:
o index.html
o lambda_function_updated.py
Step 1: Setup DynamoDB
o DynamoDB instances are specific to the AWS region selected in the top right of the AWS
console window. Ensure you have the correct region selected before creating your table:
AWS Academy ONLY allows you to perform these operations in us-east-1 and us-west-
2 regions. We select Region us-east-1 first, and then search for DynamoDB and click it.
o In the Create DynamoDB table window, enter a name for your table and a primary key.
In this example, we create a votting_table table with id as the primary key. You can then
accept the default settings and click on Create.
o Once your table is created, select Create Item from Actions to create a few items to be
stored in your table, as shown below. Note: When creating an item in your table, you need
to Add a new attribute – Count (which is a Number) on the item in addition to the key
field id.
11
o Create the following three items with id and Count as following:
You have now successfully created your DynamoDB table which we can query from your
Lambda function.
Step 2: Create your Lambda Function
Open the Lambda service and ensure the Functions dashboard is selected. Note: please
create your Lambda function in the same region as the DynamoDB you have already created.
o Select Create function and give your function a name – lambda_function in this
exercise. Use Python 3.8 as the Runtime and Use an existing role as the Execution role.
12
Note: AWS Academy provides restricted access to students on creating roles as well as
several other Identity and Access Management related tasks.
Therefore, in this exercise, we will use Use an existing role option and select a role that
AWS Academy already created for us. Select LabRole from the drop-down list.
o Click Create function.
o After the function created, you will automatically enter the function and see this interface.
Scroll down and you will see the default function code, we don’t need this.
Please copy the code in the provided lambda_function_updated.py and place on it.
13
Let’s briefly talk about what we are doing here.
1. First, we call the library used for accessing DynamoDB.
2. Then for simplicity, we directly classify GET, OPTIONS, and UPDATE request here.
• If it is GET request, we just query the current status of DynamoDB and return the
amount of vote.
• OPTIONS requests are what we call pre-flight requests in Cross-origin resource
sharing (CORS). They are necessary when you're making requests across
different origins in specific situations. This pre-flight request is made by some
browsers as a safety measure to ensure that the request being done is trusted
by the server. Meaning the server understands that the method, origin, and
headers being sent on the request are safe to act upon. Your server should not
ignore but handle these requests whenever you're attempting to do cross origin
requests.
14
• Otherwise, it is UPDATE request, we get the current status of the candidates, and
update the count by increasing 1, then return the amount of updated vote.
3. We need to correctly include CORS headers in the responses in our lambda handler.
Now please Save the file and Deploy.
o Now you can test your Lambda function.
o In Configure test event window, select Create new test event as Test event action.
In Configure test event window, give it an Event name.
Set Event sharing settings as Private.
Update Event JSON as shown below.
15
o Click Save and then Test.
16
o Verify that your function executes successfully.
The Count is increased by 1 now, if you now go to DynamoDB, then you will see the Count
of Potato will be 1. You can test with update function as well.
Now the back-end function is also ready, let’s move to the API Gateway.
Step 3: Create an AWS API Gateway
o Go to your Lambda function lambda_function, click the ‘Add Trigger’ button.
17
o Set the Trigger configuration as shown below.
Choose REST API and Open for Security.
Be friendly reminded that Open means everyone could access your API gateway.
Note: The more security approach is to set API access key but we want to simplify it so
choose Open. In Additional settings we could leave it by default.
o Click Add.
18
o Now we could see API Gateway appears on the trigger position. Just click on it.
o The below will show the details of API Gateway. Be friendly reminded that anyone who
own your API endpoint could use your API since you set to public before.
Don’t show this to others!!!!
o Now click “lambda_function-API”. It leads us to the API Gateway.
o The first thing we should do is to delete the ANY method. Tap ANY, then Delete.
19
o Then create our own POST method.
20
Important!!! Please do NOT check the “Use Lambda Proxy integration”.
Then select the Lambda function name, normally you type few words then you could
search it. The region by default is the same as your Lambda function.
Click Create Method.
o On the Resources page, tap /lambda_function, then click Enable CORS.
Cross-origin resource sharing (CORS) is a mechanism for integrating applications. CORS
defines a way for client web applications that are loaded in one domain to interact with
resources in a different domain. You can find out more here.
21
o Check POST, leave others by default, and Save.
As you can see, after CORS is enabled on the POST method, an OPTIONS method is added
to the resource, if it is not already there. The 200 response of the OPTIONS method is
automatically configured to return the three Access-Control-Allow-* headers to fulfill pre-
flight handshakes.
22
You can now test your API in the TEST tab.
We just test like before in lambda function.
23
Tap “Test”, we get the same response now. (Note: the Count is 2 now.)
o Go back to the Resources page, Click Deploy API in the upper right corner.
24
o Give a name to the stage: Production.
25
o To find the API endpoint, you need to go to your Lambda function, open Configuration
tab, click on trigger, please copy the URL for later use.
Now the API Gateway is done, then the final part is our front-end.
26
Step 4: Uploading the index.html into Amazon S3
o Before we upload our index.html, please paste the API endpoint URL to the url parameter
in index.html..
Let’s look at the index.html: In JavaScript, there are three functions: get(), update(clicked_id)
and graph().
• The get() function will post a request to get the current status, and then call the graph()
function to display the chart.
• The update(clicked_id) will get the id when we click “support” button, then it will
increase the count of the candidate, also will call the graph() function to update the
chart finally.
• asyn: false is set to avoid the delay of updating chart. If you do not care the chart does
not respond on real-time, you can change it as asyn: true.
• In addition, if there are more candidates, we could just simply add the dictionary list
and edit a little bit on graph() function.
27
o In the control panel, search S3 and select the first one. S3 is nothing but just used for
storing any objects e.g. text file, logging, videos, photos and so on.
o Click Create bucket and choose any name (must be unique) you like. Click Create bucket.
o Upload index.html to the bucket created.
o Click on index.html.
o Then click Open to see the voting system now!
If you click on Object URL, an Access Denied error will be returned by the web browser
since the object isn't publicly accessible.
Please learn more about how to configure a static website on Amazon S3.
You can use Amazon S3 to host a static website. On a static website, individual webpages
include static content. They might also contain client-side scripts. By contrast,
a dynamic website relies on server-side processing, including server-side scripts, such as
PHP, JSP, or ASP.NET. Amazon S3 does not support server-side scripting, but AWS has
other resources for hosting dynamic websites.
(Reference: https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html)
Terminate all your AWS resources after this lab to avoid unnecessary extra costs.
28