Get and Put data Using Lambda and DynamoDB, simple and clear

Mathias Zunino
Mathias Zunino
February 7, 2020
Integration
Lambda
API
Get and Put data Using Lambda and DynamoDB, simple and clear

Intro

This article was born with the objective and purpose of encouraging all readers to get into the AWS world. In this case, we will use two service providers from the AWS platform, those being Lambda and DynamoDB (NoSQL database).

Requirements:

A) - You must have an Amazon Web Services (AWS) - Cloud Computing Services account. Creating an account only requires a credit card and the usage is free as long as you don’t reach the amount of 1M (Million) requests. In this simple example, we use less than 15 requests.

B) - A code/text editor like VSCode, Atom, or other.

C) - Some knowledge of JavaScript and NodeJS (i.e. basic programing skills).

Let's get started with our example.

First things first…

Our main goal is to READ some values (data) from DynamoDB and also to WRITE some data into DynamoDB.

Set up the DynamoDB inside your AWS account.

Lambda & DynamoDB




Click on “Service” and the screen will show you a search bar. Start typing “Dynamo” in the search bar and in the list below you will see the option “DynamoDB”, go ahead and click it. Once you are there you will see the following screen:

Lambda & DynamoDB





Click the “Create table” button...yes, the big blue button.


After that you will see this:

Lambda & DynamoDB




1 - Write a name to give to your table. For example: “Users”.

2 - Here we need to add the Primary key attribute for our table, let's write: “id”, and leave the type of this value as String.

When you finish with these two steps, go ahead and click Create. Again, that’s the big blue button.

Now the table has been created inside our Dynamo Database.

Lambda & DynamoDB




You can see here a summary of information about the table, and some options. Something very important about the information listed here is the value of Amazon Resource Name (ARN). Scroll down and copy the value and save it, we will need it to create our Policies.

Now we need to go and add some records inside the table. In order to do that, click over the “Items” tab.

Lambda & DynamoDB




Here just click on “Create Item”. An Item in this database is a simple JSON object. For our example we will add this one:

Lambda & DynamoDB




Just copy and paste the object inside the following window:

Lambda & DynamoDB





Here you have two views: tree and text. In this case, choose text; this doesn't change anything important for the example, but we do it in order to better visualize the JSON object we use in this view.

Last but not least, we need to add some permissions and policies in order to use our DynamoDB with some Lambda function. Go to the service menu option. In the search bar, type “IAM”.

Lambda & DynamoDB




Lambda & DynamoDB




Click over “Roles”, and then click the big blue button with the “Create role” label.

Now just 3 more clicks:

1 - On "AWS services" in order to specify what kind of permission we want.

2 - Select Lambda service to apply for the new permission over this service.

3 - Finally click on the "Next: Permissions" button to continue the setup.

Lambda & DynamoDB




Lambda & DynamoDB




Here we need to search for “AWSLambdaBasicExecutionRole”, and check it.

This gives our future Lambda functions the permission to perform some basic tasks, like reading from and writing to the DynamoDB.

Skip step 3, as for this example we don’t need to use tags.

Finally, let’s choose a name for our Role and click on the “Create role” button.

Lambda & DynamoDB




Once we finish this step, we can then attach Policies to our role.

Lambda & DynamoDB




To do this, you need to first click on “Add inline policy”.

Once you are on this screen, follow these steps:

Lambda & DynamoDB




1 - Expand the Service menu, perform a search in the Search Bar for DynamoDB and select it.

2 - In the Actions menu, you will see Manual actions, click on “add actions”. This will display a modal window, you need to give a name to your action. Let’s type “GetItem” in the input box and click add. Then we’ll do this step again, but change the name of the second action for “PutItem”. And click Add. In conclusion, you just add two custom actions, GetItem and PutItem.

3 - Go to the Resources menu a bit below and expand it. You will see the option to “Add ARN”.

Well, this is the moment when we use the ARN that we saved previously in some text block notes.

Click on “Add ARN”. A new modal window is displayed in front of you. Copy and paste the saved ARN to the first field of this modal window.

You will notice that right after you paste the ARN, the fields below are now filled with new values.

That's okay, just leave it as it is.

Lambda & DynamoDB




Save the changes.

And just make a click on the “Review policies” button.

Finally, give a name to this policy and click the “Create policy” button.

Lambda & DynamoDB



Okay, that’s all for the moment here in DynamoDB. Let’s jump into the Lambda now.

Go to the service menu option. In the search bar we’ll now type “Lambda”.

You will see the option below, click it. Once there, click the “Create Function” button, big orange button this time.

Lambda & DynamoDB




Here is where we have the basic setup for the environment where our function will run.

Lambda & DynamoDB



We can choose from different Runtimes, but for this example we’ll choose Node.js version 12. Also, we can put a name to our function: “getUserData” and “putUserData” sounds good. Let's click “Create Function” again, and start with getUserData. Okay, now let's focus on the Function Code segment of this screen. You will see a code editor there, with a sidebar. There you can find a folder with the name of your function, and inside that folder, there is a file named “index.js”.

Lambda & DynamoDB




All this is automatically generated by Lambda Service.

Let’s jump into the editor and write some code then.

Lambda & DynamoDB




In line 10 we start our main function, and what better way to do it than using an asynchronous function.

Right after this, in line 12, we set a const documentClient in order to save the Dynamo value for region. Why do we do this? Because the request that we will send trying to fetch some data needs this value in order to match the policy and apply the permission to read from the database.

Here in line 15 we will set a constant called param. We will assign a JSON object to this constant. This object specifies the following properties: TableName: to make reference to our table Users in DynamoDB and Key object with the property id, to match the id that our record (item) has. With these values, we are telling our function FROM where we want to fetch the values and what value matches the record searched.

And finally, in line 22 we execute a try/catch block. Inside the try, let’s set another constant, called data, assigning this constant to an await function that contains the previous constant that we set above documentClient. And we will need the get function from this operation with the parameter params (our JSON object). And because this exists inside the await, we need to set a .promise() function at the end to let the NodeJS compiler know that we will have a value from this. All this block goes inside the try statement. Also, add a console.log(data) in order to display in the terminal the data that we retrieve if we don’t have any errors.

Inside the catch statement, put a simple console.log(err). If we get some error in response to our request for data, we want to display it too.

Save the changes by clicking the orange “Save” button above the editor’s right side. Now display the combo box next to the TEST button and select “Configure test events”.

Lambda & DynamoDB



Here you only need to click in the “Create” button below. The data inside the editor is just some example data, in JSON format. If you want to put one key with the same value id, go ahead, but it’s only for testing purposes.

Now let’s click on “Test” and see if we have success retrieving data from DynamoDB.

Lambda & DynamoDB




And there you have it: you get the values from the record in DynamoDB.

Now let's go ahead and try to put some records inside DynamoDB. We need to set a new function. To do this, go to the navigation path below the green success banner and click on “Functions”.

Create a new function and name it. This time use “putUserData”. Then click “Create”. You will see the code editor again. In the sidebar this time we have a folder named “putUserData” and an “index.js” file.

Now let’s add the code.

Lambda & DynamoDB




We will use 98% of the previous code that we used in the getUserData() function, but with some minor changes. Let’s take a look:

In line 12 we change Key (object name) for Item, because DynamoDB recognizes the records inside our table like items.

Line 13
: put a different value in the id property. We don’t want two users with the same id.

Line 14
: now add the firstname property and put some value. In the example I use “Mike”.

Line 15: let’s add a lastname property too. And last but not least, this function needs to tell the compiler that we need to make an insertion in the database. For that reason, we need to change the function get(), for put() in line 20. Save the changes.

Go ahead and generate a test event for this function too, like the last time.

And now test the function using the test button.

If all looks fine and you don’t see any error log, go to the Service menu, choose DynamoDB again and click it.

Let's see if our function makes the insert into the database:

Lambda & DynamoDB




Well done, we have a new record with the values that we put inside the function. Now you can play around with these two functions in order to create more user and fetch data with getUserData() to check it.

Conclusion:

Using these tools can improve your API or software implementation. You can consume your functions or use it directly in the cloud, which is also one of the benefits of cloud computing.

Imagine having triggers that execute some functions that you can have inside Lambda when some state of your API changes, or when you get some event requested from the client or backend of your application. There’s a whole world of possibilities related to cloud computing, and this tutorial is just the kickoff to encourage you to explore and dive deeper into it.

Don't miss a thing, subscribe to our monthly Newsletter!

Thanks for subscribing!
Oops! Something went wrong while submitting the form.

Serverless GraphQL API with Hasura and AWS stack

As a follow-up to our serverless REST API post, this article provides a thorough step-by-step guide on how to creating a GraphQL API boilerplate based on Hasura and the AWS stack.

May 5, 2020
Read more ->
Serverless
API
GraphQL
AWS
AWS Benefits

Setting a GraphQL endpoint using AWS Lambda functions

In this article we will see how easy it is to set a GraphQL endpoint using AWS Lambda functions.

November 2, 2020
Read more ->
GraphQL
AWS
Lambda

Contact

Ready to get started?
Use the form or give us a call to meet our team and discuss your project and business goals.
We can’t wait to meet you!

Write to us!
info@vairix.com

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.