Deploying and Configuring Lambda Functions for Our API Using the AWS Console

Hands-On Lab

 

Photo of Fernando Medina Corey

Fernando Medina Corey

Training Architect

Length

01:00:00

Difficulty

Intermediate

AWS Lambda is a compute service that lets you run code without provisioning or managing servers. AWS Lambda executes your code only when needed and scales automatically, from a few requests per day to thousands per second. You pay only for the compute time you consume - there is no charge when your code is not running. With AWS Lambda, you can run code for virtually any type of application or backend service - all with zero administration. In this lab you will learn how to use the AWS console to configure and deploy AWS Lambda functions. You will be provided login information for the AWS console and then proceed to use pre-written function code to configure and deploy the first two functions of our application. To complete this lab, go to github.com for the pre-written code.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Lambda Functions in the Console

In this lab, we are working for the company PrometheonPartners. We have been tasked to configure and deploy AWS Lambda functions. Using pre-written function code, we will configure and deploy the first two functions of our application.

Create a create Function

Sign in to the AWS Console with the account and password given. Once logged in, select Lambda from either under Recent, or select the Services dropdown, scroll down to Compute, and select Lambda from the list.

There will already be a function present. Don't mind it as it is there to support the environment. We won't be doing anything with it.

Select Create Function, then Author from Scratch. For this application, name our function create, set our Role to Choose an existing role from the drop-down, and for Existing role select DynamoDBFullLambdaAccess. Select Create Function.

Configure your Function

With our function created, we can get started with our configuration.

To set up the Function Code section, set Code entry type to Edit code inline, Runtime to Node.js 6.10, and Handler to index.create.

Open the create.js file from github. Copy the information in the file. Delete the information already present in the Function code and replace it with the copied code. Once we finish pasting, look for the code line that starts module.exports.create, it is near the top. This line is where we get the create portion for our Handler. The index stands for our index.js file itself while the create handles the function stored inside of the index.js file.

While there are other items we can set for this function, we are using all of the default settings. Select Save.

Breaking down create.js

While the code is already provided for you, it is important to know how it works. While some of this will be similar to our previous labs, other parts will perform new actions.

For this code, we are using the use strict command.

'use strict';

The first portion of the code goes over what will be required to run it, where it will be run, and for what client. In this instance, we will need aws-sdkto run the process. Our region tells our script where this will be run, our documentClient designates that it will be working with DynamoDB, which makes it easier to run with the Java SDK.

const AWS = require('aws-sdk');
AWS.config.update({region:'us-east-1'});

const dynamoDb = new AWS.DynamoDB.DocumentClient();

This section of code outlines our Handler function that we set. This is where it pulls the .create from. It takes the results of the event body, parses it, and then returns the information as the data variable.

module.exports.create = (event, context, callback) => {
  const data = JSON.parse(event.body);

The following code sets up the parameters for the information brought into the function. You may recognize the table PrometheonMusic, as we have used it in prior labs. The coding designates what parts of an item will be pulled in from the table.

  const params = {
    TableName: 'PrometheonMusic',
    Item: {
      Artist: data.Artist,
      SongTitle: data.SongTitle,
      AlbumTitle: data.AlbumTitle,
      CriticRating: data.CriticRating,
      Genre: data.Genre,
      Price: data.Price
    },
  };

  // write the item to the database

This portion of the code is to let us know if there are any errors when running the deletion script. If so, an error is logged, and we are alerted.

  dynamoDb.put(params, (error) => {
    // handle potential errors
    if (error) {
      console.error(error);
      callback(null, {
        statusCode: error.statusCode || 501,
        headers: { 'Content-Type': 'text/plain' },
        body: 'Couldn't create the item.',
      });
      return;
    }

This last section defines the callback of the information parsed from the params.Item.

    // create a response
    const response = {
      statusCode: 200,
      body: JSON.stringify(params.Item),
    };
    callback(null, response);
  });
};

With this code as a whole, we can create a new item for our PrometheonMusic table.

Once done, select Save.

Test the Function

Once the save is finished, select Test to start a test. But we can't just start a test; we need to create a test event first. Since we didn't have a test event selected, we end up on the Configure test event page.

Open the createTest.json file on github. Take the code from the file and paste it into the event code. Name the event createTest and leave the event template as Hello World.

Select Create.

We are taken back to the create page. Next to the Test button, the test event we created appears. Now, when we select Test, it will run. Once the test completes, a message appears stating Execution result: Succeeded.

To review the details, select the Details dropdown.

Run the Function

With our test telling us that our function now functions, we can use it. To do so, we head over to the DynamoDB section. In DynamoDB, select Tables from the sidebar and select the PrometheonMusic table and then the Items tab.

Using Query, search for the items we put into our function from the create.js. In case you don't remember what these items were, for Artist, it was TestArtist, and SongTitle was Test Song.

Run the query. Once it finishes, the item will appear, meaning that our Lambda function was created correctly and it has created the item in our table.

Create a get Function

Let's create a second function; this one will be a get function. Head back to Lambda and Functions. Ignore both of our functions, and select Create Function. A series of blueprints appear, but we aren't using any of those. Select Author from scratch. Name this function get and choose our DynamoDBFullLambdaAccess role from the Existing role dropdown. Select Create Function.

As with our first function, set the Code entry type to Edit code inline, the Runtime to Node.js6.10, and Handler to index.get. Go to GitHub and select the get.js file, then copy the information in the file. Delete the information already present in the Function code and replace it with the copied code.

The code for this function is very similar to our create function, but the module.exports section is different. Instead of ending in create it ends in get. Along with that, the const params={ section holds only information over the Keys used to query, that being the Artist and SongTitle.

module.exports.get = (event, context, callback) => {
  const data = JSON.parse(event.body);

  const params = {
    TableName: 'PrometheonMusic',
    Key: {
      Artist: data.Artist,
      SongTitle: data.SongTitle
    },
  }

With this information pasted in, select Save and then Test.

As before, we are asked to either select a pre-made test template or to create one. Create a new one and name it getTest. Go to GitHub and select the getTest.json file and then copy and paste the information into the test event. Select Create.

With it created, select Test. It will appear as succeeded.

Other Functions

While this only uses create and get, in later labs we will be using other functions as well. The following information reviews the similarities and differences between all of these functions in comparison to the ones you have already created.

update Function

update takes new information and overwrites what is already there.

module.exports.update = (event, context, callback) => {
  const data = JSON.parse(event.body);

The params section has the biggest changes compared to the get, and create functions. As you can see below, a line called UpdateExpression is present. This line designates that all of the information following it will be updated. Then, the ExpressionAttributeValues section tells the UpdateExpressions what those set items will become.

  const params = {
    TableName: 'PrometheonMusic',
    Key: {
      Artist: data.Artist,
      SongTitle: data.SongTitle,
    },
    UpdateExpression: "set AlbumTitle=:AlbumTitle, CriticRaging-:CriticRating, Genre=:Genre, Price=:Price",
    ExpressionAttributeValues:{
      "AlbumTitle": data.AlbumTitle,
      "CriticRating": data.CriticRating,
      "Genre": data.Genre,
      "Price": data.Price
    },
    ReturnValues:"ALL_NEW"
  };

The rest of the code is almost identical to the previous types, only with the addition of update where before it said create or get.

delete Function

The delete does the opposite of our create. Whatever is designated will be removed from a table instead of being added to it.

module.exports.delete = (event, context, callback) => {
  const data = JSON.parse(event.body);

The alerts also change to let us know an item couldn't be deleted.

  dynamoDb.delete(params, (error, result) => {
    // handle potential errors
    if (error) {
      console.error(error);
      callback(null, {
        statusCode: error.statusCode || 501,
        headers: { 'Content-Type': 'text/plain' },
        body: 'Couldn't delete the item.',
      });
      return;
    }

list Function

module.exports.get becomes module.exports.list and it creates a limit for the function. This sets how many items will be listed. The biggest difference between list and get is that get pulls a specific item while list pulls the first ten items starting with the first item in a table, unless designated otherwise.

module.exports.list = (event, context, callback) => {
  const data = JSON.parse(event.body);

In the warnings section, the information is based on results with the content warning appearing when the code can't fetch an item.

dynamoDb.scan(params, (error, result) => {
    // handle potential errors
    if (error) {
      console.error(error);
      callback(null, {
        statusCode: error.statusCode || 501,
        headers: { 'Content-Type': 'text/plain' },
        body: 'Couldn't fetch the item.',
      });
      return;
    }

Review

Upon completing this lab, you not only know how to use the create and get functions but also have had a general introduction to functions you will be using in future labs. Congratulations on completing the lab!