[go: up one dir, main page]

0% found this document useful (0 votes)
25 views22 pages

5CS022 - AWS Lambda REST API

This document outlines a workshop for creating and deploying a REST API using AWS Lambda and Amazon API Gateway. It includes tasks for creating Lambda functions, integrating them with API Gateway, deploying the API, and testing it. Additionally, it covers the creation of a multi-function calculator REST API and configuring static web hosting using Amazon S3.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views22 pages

5CS022 - AWS Lambda REST API

This document outlines a workshop for creating and deploying a REST API using AWS Lambda and Amazon API Gateway. It includes tasks for creating Lambda functions, integrating them with API Gateway, deploying the API, and testing it. Additionally, it covers the creation of a multi-function calculator REST API and configuring static web hosting using Amazon S3.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

University of Wolverhampton

School of Mathematics and Computer Science

5CS022 Distributed and Cloud Systems


Programming
Workshop 4 - Using AWS cloud service to create a REST API
with AWS Lambda
Part 1
Overview
In this workshop you will create and deploy a REST API with a Lambda proxy integration and a
Lambda non-proxy integration in Amazon API Gateway.

In a Lambda integration, the HTTP method request from the client is mapped to a backend Lambda
function invocation.

In a Lambda proxy integration, the entire client request is sent to the backend Lambda function as is,
except that the order of the request parameters isn't preserved. API Gateway maps the entire client
request to the input event parameter of the backend Lambda function. The Lambda function's
output, including status code, headers, and body, is returned to the client as is. This is more like a
traditional web application.

In a Lambda non-proxy integration, you configure the way the parameters, headers, and body of the
client's request are translated into the format that your backend Lambda function requires. And you
configure the way the Lambda function output is translated back to the format that's required by the
client.

You will need to use the Google Chrome web browser for this workshop.

Task 1. Create a Lambda Function in the Lambda Console

Use last workshop's steps to create a "Hello World" Lambda function, identical in every way except
that you should call the function "my-function" instead of "hello-world-python", and instead of
"Hello world" or "Hello from Lambda", put in "Hello your-student-id your-name", for example, "Hello
1234567 Jeffrey Ting".
Below is an example code template:

import json

def lambda_handler(event, context):


return {
'statusCode': 200,
'body': json.dumps('Hello 1234567 Jeffrey!')
}

Do not follow the " Step 6: Delete the Lambda Function" step in Workshop 1.

Task 2. Create a REST API in the API Gateway Console

In this step, you create a simple REST API in the API Gateway console and attach your Lambda
function to it as a backend.

1. From the Services menu, choose (or search) API Gateway to go to the API Gateway console.

2. You may (sometimes you may not) see a page that introduces you to the features of the
service.
Choose Get Started. When the Create Example API popup appears, choose OK. If that popup
does not appear, just choose Create API.
3. Under Choose the protocol, choose REST.
4. However, if you see this page instead:

Just click on "REST API"

5. Under Create new API, choose New API.


6. Under Settings:
a. For API name, enter my-api.
b. Enter your name and student ID in the Description field.
c. Leave Endpoint Type set to Regional.
7. Choose Create API.
8. Under Resources, you'll see nothing but /. This is the root-level resource, which corresponds
to the base path URL for your API.
9. From the Actions dropdown menu, choose Create Method.
10. Under the resource name (/), you'll see a dropdown menu. Choose GET and then choose the
checkmark icon to save your choice.
11. In the / – GET – Setup pane, for Integration type, choose Lambda Function.
12. Choose Use Lambda proxy integration.
13. For Lambda Region, choose "us-east-1".
14. In the Lambda Function field, start typing "my-function" and then choose "my-function" (the
name you gave the function that you created in the previous step) from the dropdown
menu. (If the dropdown menu doesn't appear, delete the character you just typed to make
the dropdown menu appear.) Leave Use Default Timeout checked.

15. Choose Save to save your choice.


16. When the Add Permission to Lambda Function popup appears (saying "You are about to give
API Gateway permission to invoke your Lambda function…"),

choose OK to grant API Gateway that permission.

Now you should see a / – GET – Method Execution pane:


Note for your information:

The Method Execution pane contains these items, in clockwise order:

● Client: This box represents the client (browser or app) that calls your API's GET method. If
you choose the Test link and then choose Test, this simulates a GET request from a client.
● Method Request: This box represents the client's GET request as it's received by API
Gateway. If you choose Method Request, you'll see settings for things like authorization and
modifying the method request before it's passed through to the backend as an integration
request. For this step, leave everything set to the default values.
● Integration Request: This box represents the GET request as it's passed to the backend. Here
the settings depend on the Integration Type that's selected. The URL Path Parameters, URL
Query String Parameters, HTTP Headers, and Mapping Templates settings are for modifying
the method request as needed by the specific backend. Leave the Integration Type set to
Lambda function, and leave the other settings set to the default values.
● Lambda my-function: This box represents the backend Lambda function you created
previously. If you choose my-function, that opens the my-function Lambda function in the
Lambda console.
● Integration Response: This box represents the response from the backend, before it's passed
to the client as a method response. For a Lambda proxy integration, this entire box is greyed
out, because a proxy integration returns the Lambda function's output as is. For a Lambda
non-proxy integration, you can configure the integration response to transform the Lambda
function's output into a form that's appropriate for the client application. Just leave
everything set to the default values.
● Method Response: This box represents the method response that's returned to the client as
an HTTP status code, an optional response header, and an optional response body. By
default, the response body that's returned by your Lambda function is passed through as is
as a JSON document, so the response body default setting is application/json with an empty
model (indicating that the body is passed through as is). Leave everything set to the default
values.

Task 3. Deploy your REST API

You have now created an API, but you can't actually use it yet. This is because it needs to be
deployed.

1. From the Actions dropdown menu, choose Deploy API.

2. From the Deployment stage dropdown menu, choose [New Stage].


3. For Stage name, enter prod.
4. Choose Deploy.
5. If you get a warning about permissions:

just ignore it and close it. It does not affect us.


6. In the prod Stage Editor, note the Invoke URL at the top. It should be in this format:
(https://qewc68m869.execute-api.us-east-1.amazonaws.com/prod). The " qewc68m869" bit
is your API ID. Make a note of this. Copy it to somewhere safe.
7. Click "Save Changes"
8. Click on the URL, it will open a new browser tab with that URL. If you refresh the new
browser tab, you'll see the message body ("Hello 1234567 Jeffrey!") or what ever your ID
and name is, that you put into the Lambda function.

Task 4. Create a Second Lambda Function in the Lambda Console

You will now create a second backend Lambda function. This one takes an input parameter. In Step 5
you'll create a child resource in your API that has its own GET method, which you'll configure to pass
a parameter value to this new function.

1. Choose Lambda from the Services menu to go to the Lambda console.


2. Choose Create function.
3. Choose Author from scratch.
4. For Function name, enter my-function2.
5. Under Runtime, choose Python 3.7 (or whichever Python 3 version that is available to you)
6. Under Permissions, expand Choose or create an execution role. From the Execution role
dropdown list, choose Use an existing role. From Existing role, choose the role from your
previous Lambda function. The role's name will be in the form service-role/my-function-
a1b23c4d. Or choose Create a new role with basic Lambda permissions.
7. Choose Create function.
8. In the Function code pane, you'll see the default "Hello from Lambda!" function. Replace the
entire function with the following:
import json

def lambda_handler(event, context):

myParam = event['myParam']

return {

'statusCode': 200,

'body': json.dumps(myParam)

9. Then choose Save.


10. Click "Deploy"

Task 5. Add a Resource, Method, and Parameter to the REST API in the API Gateway Console

Resources and methods are the nouns and verbs of your REST API. In this step, you'll create a child
resource for the API and add a GET method to the resource. You'll add a query string parameter to
the new method to match the input parameter for the Lambda function you created in Step 4. You'll
integrate the new function with the method to illustrate how to get user input (a simple "Hello from
API Gateway!" text string) and map it to the Lambda function's input (also a simple string).

1. Choose API Gateway from the Services menu to go to the API Gateway console.
2. From the APIs list, choose my-api.
3. Under Resources, choose /.
4. From the Actions dropdown menu, choose Create Resource.
5. For Resource Name, enter my-resource. Notice that the Resource Path field is populated
automatically with the resource name.
6. Choose Create Resource.
7. From the Actions dropdown menu, choose Create Method.
8. Under the resource name (my-resource), you'll see a dropdown menu. Choose GET and then
choose the checkmark icon to save your choice.
9. In the /my-resource – GET – Setup pane, for Integration type, choose Lambda Function.
10. For Lambda Region, choose the Region where you created your Lambda function.
11. In the Lambda Function box, type any character and then choose my-function2 from the
dropdown menu. (If the dropdown menu doesn't appear, delete the character you just
typed to make the dropdown menu appear.) Choose Save to save your choice.
12. When the Add Permission to Lambda Function popup appears (saying "You are about to give
API Gateway permission to invoke your Lambda function…"), choose OK to grant API
Gateway that permission.
13. You'll now see a /my-resource – GET – Method Execution pane. Notice that this time the
Integration Response box is not greyed out. Choose Integration Request:

14. Expand Mapping Templates.


15. Set Request body passthrough to When there are no templates defined.
16. Choose Add mapping template.
17. For Content-Type, enter application/json and choose the checkmark icon to save your
choice.
18. If a Change passthrough behaviour popup appears, choose Yes, secure this integration. This
ensures that your integration only allows requests that match the Content-Type you just
defined.
19. In the template window, enter the following:

{
"myParam": "$input.params('myParam')"
}

This is the JSON document that will be passed to your Lambda function in the body of the
input event object. The right-hand side tells API Gateway what to look for in your input
query string. The left-hand side stores it into the parameter that you're about to add to your
Lambda function.
20. Choose Save.
21. From the Actions dropdown menu, choose Deploy API.
22. From the Deployment stage dropdown menu, choose prod.
23. Choose Deploy.
Task 6. Testing your REST API

1. With a new web browser, go to :

https://b123abcde4.execute-api.us-east-1.amazonaws.com/prod

Make sure you replace the "b123abcde4" with your API ID.
This will invoke your API, and you'll see "Hello from 1234567 John Smith" returned. This is
because your new Lambda function, my-function2, isn't attached to the root resource (/). It's
attached to the new resource you created, my-resource. So the Lambda function you just
invoked is the original function you created earlier, my-function.

2. With replace the URL in the browser with :

https://b123abcde4.execute-api.us-east-1.amazonaws.com/prod/my-resource?
myParam=Hello%20John%20Smith%20from%20API%20Gateway!

Make sure you replace the "b123abcde4" with your API ID. You should now see the correct
response returned: {"statusCode": 200, "body": "\"Hello John Smith from API Gateway!\""}.

3. Change the "John Smith" bit in the URL to your own name, and repeat.

Part 2 - Creating a multi-function calculator REST API with


AWS Lambda (assessed)
Overview
In this part you will use what you have learnt so far to create and deploy a multi-function calculator
REST API with AWS Lambda and Amazon API Gateway.

You will need to use the Google Chrome web browser for this workshop. You will also need to take a
number of screen captures as evidence of you progress, as well as the code that you will be creating,
for the submission for this workshop. Start a New Microsoft Word document and paste these screen
captures in and to paste your code in.

Task 1. Create a new Lambda Function in the Lambda Console

Create a new Lambda function, and call the function "addition" and put in the following code:
import json
def lambda_handler(event, context):
A = event['A']
B = event['B']
C = int(A) + int(B)
return {
'statusCode': 200,
'body': json.dumps(C)
}

Testing your function

Create a new test event and put the following test event code in:

{
"A": "15",
"B": "3"
}

Test your Lambda function with this test event and you should get:

Assessment task. (8%)

Capture this screen and paste it into your Word file for your assessment submission.

Task 2. Create a REST API for addition

Use what you have learnt so far, to create new REST API in the API Gateway console and attach your
Lambda function to it as a backend. Make sure that the new API is called "my-calc".

Add a Resource.Call your new Resource "addition"


Create a GET method and attach it to your "addition" function,

Select Integration Request and create a mapping template with the following:

{
"A": "$input.params('A')",
"B": "$input.params('B')"
}
Save and deploy this new resource to a new prod stage.

Now test your new calculator REST API by going with a web browser to :

https://fg7mltsiyg.execute-api.us-east-1.amazonaws.com/prod/addition?A=3&B=4

Obviously, replace the "fg7mltsiyg" with your REST API id. And you should get something like the
following:

Assessment task. (8%)

Capture this screen and paste it into your Word file for your assessment submission.

Assessment task. (24%)

Create 3 more Lambda functions for subtraction, multiplication and division, as well as their
associated REST API Resources. Call the Resources " subtraction", "multiplication" and "division"
and attach them to the corresponding Lambda functions.

Submit the Lambda function code for each function in your Word file, as well as the corresponding
screen captures of each of the REST API outputs, when you call them in the web browser.
Task 3. Creating a web front end to call the REST APIs

1. In the AWS API Gateway for each of the API Resource, click on the Actions and then click on
"Enable CORS":

2. On the next screen, click on "Enable CORS and replace…":

3. Just to be on the safe side, Deploy API again.

Task 4. Static Web Hosting


In this task you'll configure Amazon Simple Storage Service (S3) to host your web page.

Your end users will then access your site using the public website URL exposed by Amazon S3. You
don't need to run any web servers or use other services in order to make your site available.

The first thing that you need to do is to make sure that you have the correct region for you
application. Make sure that you have selected "us-east-1"

Task 4. Creating an S3 bucket

Amazon S3 buckets can be used to host static websites without having to configure or manage any
web servers.

In this step, you will use the console to create an Amazon S3 bucket. Keep in mind that your bucket's
name must be globally unique. Use the name format "calc-student-id-yourname". If you get an error
that your bucket name already exists, try adding additional characters until you find an unused
name. Make sure that your student ID and your name is in the bucket name.

In the AWS Management Console search and select S3. Choose "Create Bucket".
Provide a unique name for your bucket such as calc-student-id-yourname. If you get an error that
your bucket name already exists, try adding additional numbers or characters until you find an
unused name.

Make sure that the Region is "US East (N. Virginia)". Choose Create in the lower left of the dialog
without selecting a bucket to copy settings from.
Then further down, clear all the "Block all public access " checkbox and check the "I acknowledge…"
box:

Accept the other default options and then click "Create bucket".

You should end up back in the console with your newly created S3 bucket:
Task 6. Uploading Content

1. Download the file "calc.html" from Canvas.


2. Edit the calc.html in either Notepad or your favourite text editor (but not MS Word).
3. Replace the REST API url in file with your own:

4. Select the bucket you created in the previous step and ensure you are viewing the Overview
tab.

5. Click "Upload" and then "Add files" select the calc.html file you previously downloaded and
edited.
6. Click Upload.

Task 7. Adding a Bucket Policy to Allow Public Reads

You can define who can access the content in your S3 buckets using a bucket policy. Bucket policies
are JSON documents that specify what principals are allowed to execute various actions against the
objects in your bucket.

In this step, you will add a bucket policy to your new Amazon S3 bucket to let anonymous users view
your site. By default your bucket will only be accessible by authenticated users with access to your
AWS account.

1. In the S3 console, select the name of the bucket you created.


2. Go to Bucket Policy.
3. Enter the following policy document into the bucket policy editor replacing
[YOUR_BUCKET_NAME] with the name of the bucket you created:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::[YOUR_BUCKET_NAME]/*"
}
]
}

For example:

4. Do not change the version string. It is not meant to be today's date.


5. Choose Save to apply the new policy

Task 8. Enabling Website Hosting

By default objects in an S3 bucket are available via URLs with the structure
http://.amazonaws.com//. In order to serve assets from the root URL (e.g. /index.html), you'll need
to enable website hosting on the bucket. This will make your objects available at the AWS Region-
specific website endpoint of the bucket: .s3-website-.amazonaws.com.

In this step, you will use the console to enable static website hosting. You can do this on the
Properties tab after you've selected the bucket. Set calc.html as the index document, and leave the
error document blank.
1. From the bucket detail page in the S3 console, choose the Properties tab.

2. Scroll down to the Static website hosting card.

3. Click Edit and then select "Enable".


4. Enter calc.html for the Index document.

5. Click Save to save your changes.

Task 9. Testing your implementation

1. You should be able to access your web page by visiting the website endpoint URL for your S3
bucket.
2. Go to your "Bucket website endpoint":

And click on the link. You should see the home page displayed.
3. Enter numbers for "A" and "B", and click on one of the function button:

You might also like