Kyle Pericak

"It works in my environment."

Wed 08 January 2020

AWS Lambda: Basics

Posted by Kyle Pericak in cloud   

This post is linked to from the AWS: Deep Dive Project

This post covers the basics of using AWS Lambda functions.


For the most accurate data, see the official pricing documentation.

Lambda charges you for each request invocation, and also for how long the request took to run. These prices are probably in USD.

  • Region: Canada (Central)
  • Requests: $0.20 / 1M Requests, or $0.0000002 / Request
  • Duration (General): $0.000016667 for every GB-second
  • Duration (128MB): $0.00000208/sec, or ~$0.0075/hour. I think if it as 3/4 of a cent per hour.

Hello World Lambda Function

Create the function

  1. In your browser, open the AWS console Lambda Page.
  2. Click the orange Create Function button
  3. Author from scratch
  4. Function name: HelloWorld
  5. Runtime: Python 3.7
  6. Permissions: Create a new role with basic lambda permissions
  7. click Create Function on the bottom right

Define a test event

  1. In the dropdowns along the top, one is called "Select a test event".
  2. Click it, and choose Configure test events
  3. Event template: Hello World
  4. Event name: HelloWorldTest1
  5. Enter some sample data and click Create.

Sample Data:

  "body": "{\"name\": \"Test User\"}"

Write the function code

Click on the orange lambda icon with the text "HelloWorld" to open the "Function code" form. Expand it to full screen (button on top right) so the Save and Test buttons appear along the top.

Write your Hello World function. This was the shortest one I could come up with that wouldn't throw 500's if you called it with the wrong data.

import json

def lambda_handler(event, context):
    name = 'UNDEFINED'
    if 'body' in event:
            ebody = json.loads(event['body'])
            name = ebody['name']
    greeting = f'Hello {name}!'
    body = json.dumps(greeting)
    return {
        'statusCode': 200,
        'body': body

Click Save, then Test. You should get a response with body 'Hello TestUser'.

Define a trigger

  1. Click the "+ Add trigger" button.
  2. API Gateway
  4. Security: Open (in this case)
  5. Additional Settings: Leave the defaults

Now if you click on the purple API Gateway button it will open the API Gateway form. In there, you can get the URL. Copy the link address.

Test the API

From bash:

curl \
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{"name": "MyName"}' \

It should reply "Hello MyName".

...What are layers?

Prominently displayed beneath the function's name in the Designer form is a button to manage Layers.

Here's their official documentation.

Layers are dependencies like archives and libraries. Any one function can use up to 5 of them, and they have a 250MB limit. They land in /opt when extracted.

We don't need layers for this Hello World app.

Javascript appears to be disabled. Comments can't load.