Lab Steps

lock
Logging in to the Amazon Web Services Console
lock
Understanding RESTful APIs
lock
Defining New API Gateway Resources
lock
Creating an AWS Lambda Function Backend
lock
Versioning and Aliasing the Lambda Function
lock
Configuring the API Gateway Backend
lock
Following Best Practices for Versions, Aliases, and Stages
lock
Creating API Keys and Usage Plans
lock
Enabling CORS on API Gateway Resources
lock
Enabling API Gateway Caching and Throttling
lock
Cleaning up API Resources and Lambda Functions
live-help Need help? Contact our support team

Here you can find the instructions for this specific Lab Step.

If you are ready for a real environment experience please start the Lab. Keep in mind that you'll need to start from the first step.

Introduction

You designed and created an API Gateway resource in the previous Lab Step, but it doesn't have a real implementation yet.

In this Lab Step, you will create a new Lambda function that will handle both endpoints. This approach has the advantage of reducing the number of functions you need to maintain (and therefore the amount of code), besides partially solving the cold-start issue of AWS Lambda. The cold-start issue with Lambda is due to the initial startup phase of your functions code, which might take up to a few seconds (worst case). By having fewer functions, you increase the likelihood of keeping them warm even if you don't have a very high load.

The Lambda function you will create will dynamically check whether an Item ID or the entire list has been requested and behave accordingly. Since you already created an API, you will not use the simplified flow to create new Lambda-backed API Gateway resources. This flow is recommended whenever you start from scratch with Lambda and you don't need much in the way of API Gateway configuration, which is the norm in most simple use cases.

 

Instructions

1. In the AWS Console, click Services, enter Lambda in the search barand select the Lambda search result:

alt

 

2. Click Create a function:

alt

 

3. In the Author from scratch form, enter the following values and click Create function:

  • NameItemsFunction
  • Runtime: Python 3.x (The latest version of Python 3)
  • Role: Choose an existing role
  • Existing role: lambda_basic_execution

alt

Warningalt: The function name needs to be ItemsFunction, otherwise you won't be able to proceed.

 

4. Scroll down to the Function code section, and overwrite the contents of the lambda_function.py file with the following code:

content-copyCopy code
# static list of items
items = [
{"ID": 1, "name": "Pen", "price": 2.5},
{"ID": 2, "name": "Pencil", "price": 1.5},
{"ID": 3, "name": "Highlighter", "price": 3.0},
{"ID": 4, "name": "Ruler", "price": 5.0},
]

def lambda_handler(event, context):
print("Event: %s" % event) # log event data
ID = event.get("ID") # extract ID

# list case
if not ID:
return items

# ID case
found = [item for item in items if item["ID"] == ID]
if found:
return next(iter(found))

# nothing was found
raise Exception("NotFoundError")

alt

The function is very simple, without any specific dependency or infrastructure requirement.

The logic is quite straightforward:

  • if no ID is given, return the whole list
  • if the ID exists, return the corresponding Item
  • otherwise, raise an error

The other Lambda configuration fields can be left at their defaults.

 

5. Click Save in the upper-right corner to save the Lambda function.

You can now test the function.

 

6. Click Test in the upper-right corner:

alt

 

7. In the Configure test event form, enter the following values into the form:

  • Event nameGetItems
  • Event body: Enter the following JSON into the event editor at the bottom of the form:
    content-copyCopy code
    {}

alt

The {} represents an empty object in JSON. Because no ID is specified the test will confirm the code path for returning all the items.

 

8. Click Create.

 

9. Click Test in the upper-right corner to run the GetItems test you just created:

alt

Within a few seconds you should see a succeeded result:

alt

 

10. Click Details to expand the details of the test run:

alt

The result confirms the list of all items are returned.

 

11. Repeat the test process to test two more code paths for the following cases:

  • An object such as {"ID": 1}, which will return only one item.
  • An object such as {"ID": 5}, which will return an NotFoundError.

Please note that in a real-world scenario you'd normally perform these operations on a database (DynamoDB, RDS, Firebase, etc.). In the simple scenario of the Lab, a static list of objects in main memory is more than enough. Also, keep in mind that the code will run on multiple machines (i.e. containers) and we will not be able to update the in-memory list consistently. In fact, only GET methods are defined and no transformation on the Items are allowed.

 

Summary

In this Lab Step, you created and tested the Lambda function that will serve as the backend for your API in API Gateway. Before you can use it, it is best to understand versioning so you can use different versions of the function in the dev and stage environments. The next Lab Step will show you how to work with function versions.