Creating an AWS Lambda Function Backend
Lab Steps
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 Management Console search bar, enter Lambda, and click the Lambda result under Services:
You will see the Functions list page.
2. Click Create function:
3. In the Author from scratch form, enter the following values:
- Name: ItemsFunction
- Runtime: Python 3.x (The latest version of Python 3)
: The function name needs to be named ItemsFunction, otherwise you won't be able to proceed. Ensure that the function name matches ItemsFunction exactly, including capital letters.
4. To assign an IAM role, click Change default execution role, and select the following:
- Execution role: Select Use an existing role
- Existing role: Select lambda_basic_execution
You have a selected a role that has been created for you. The role has the necessary required IAM permissions needed to complete this lab.
5. Scroll to the bottom and click Create function:
6. Scroll down to the Code source section, double click the lambda_function.py file, and overwrite the file contents with the following code:
Copy code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 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")
Your Code source section will look like this:
The function is very simple, without any specific dependency or infrastructure requirement.
The logic is straightforward:
- If no ID is given, return the whole list
- If the ID exists, return the corresponding Item
- Otherwise, raise an error
The other AWS Lambda configuration fields can be left at their defaults.
7. To deploy your function, at the top of the Code source section, click Deploy:
You will see a notification that your function has been deployed:
You can now test the function.
8. At the top, click Test:
9. In the Configure test event form, enter the following values into the form:
- Event name: GetItems
- Event body: Replace the existing contents with the following JSON in the event editor text-area:
Copy code
1
{}
The {}
represents an empty object in JSON. Because no ID is specified the test will confirm the code path for returning all the items.
10. Scroll to the bottom and click Save.
11. Click Test at the top of the Function code section to run the GetItems test you just created:
A new tab in the code editor will load called Execution results. This tab contains the results of the test:
The result confirms the list of all items is returned.
12. 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.