AWS Lambda Examples

Contents

Intro

This is just going to be a set of Lambda sample functions that I can use to reference to speed up my development time. Examples of good formats for making DynamoDB calls and other microservices. Almost all my examples will be Javascript, but I might throw in some Python ones.

One thing to note is that even though AWS has now come out with the SDK v3, you actually want to use SDK v2 in Lambda as it is installed in the default Lambda Node.js environment.

DynamoDB

Document Client

Query

// Load the AWS SDK for Node.js.
var AWS = require("aws-sdk")
// Set the AWS Region.
AWS.config.update({ region: "us-east-1" })

// Create DynamoDB service object.
var ddb = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" })

exports.handler = async (event, context) => {
  // response variables
  let body
  let statusCode = "200"
  const headers = {
    "Content-Type": "application/json",
  }

  // request parameters
  let params = {
    TableName: "settings",
    KeyConditionExpression: "#id = :user",
    ExpressionAttributeNames: {
      "#id": "user_id",
    },
    ExpressionAttributeValues: {
      ":user": event.user_id,
    },
  }

  // request
  try {
    const data = await ddb.query(params).promise()
    console.log(data)
    body = data
  } catch (error) {
    statusCode = "400"
    body = error.message
  }

  //  dynamic response
  return {
    statusCode,
    body,
    headers,
  }
}

Batch Get

If you need to get multiple items at once, the batch get method is fantastic. Given the following event:

{
  "profiles_array": [
    {
      "profile_id": 2307521226105089
    },
    {
      "profile_id": 1363579156439011
    }
  ]
}

We can retrieve multiple items at the same time like so.

// Load the AWS SDK for Node.js.
var AWS = require("aws-sdk")
// Set the AWS Region.
AWS.config.update({ region: "us-east-1" })

// Create DynamoDB service object.
var ddb = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" })

exports.handler = async (event, context) => {
  // response variables
  let body
  let statusCode = "200"
  const headers = {
    "Content-Type": "application/json",
  }

  // request parameters

  let params = {
    RequestItems: {
      "profiles_metadata": {
        Keys: event.profiles_array
      }
    },
  }

  // request
  try {
    const data = await ddb.batchGet(params).promise()
    console.log(data)
    body = data
  }
  catch (error) {
    statusCode = "400"
    body = error.message
  }

  //  dynamic response
  return {
    statusCode,
    body,
    headers,
  }
}

and we can even get multiple items, from multiple different tables in one call!

const AWS = require("aws-sdk")
AWS.config.update({ region: "us-east-1" })
const dynamoDB = new AWS.DynamoDB.DocumentClient()

dynamoDB
  .batchGet({
    RequestItems: {
      "my-table": {
        Keys: [
          {
            id: "123",
          },
          {
            id: "124",
          },
        ],
      },
      "other-table": {
        Keys: [
          {
            id: "abc",
          },
          {
            id: "abd",
          },
        ],
      },
    },
  })
  .promise()
  .then(data => console.log(data.Responses))
  .catch(console.error)

Keep in mind that number of items retrieved using batchGet is limited to 100 items or 16MB of data.

Moreover, if you exceed table capacity, this call will return UnprocessedKeys attribute containing a map of keys which weren’t fetched.