Lambda functions with DynamoDB & Node

In this post let's use the API we previously created and create and fetch data from a database provided by AWS called DynamoDB.

DynamoDB is a fully managed proprietary NoSQL database service that supports key–value and document data structures.

So, to being with create another API with request type POST called createStudent and you can use the body property to extract request body from the event parameter in the lambda function.

Creating a DynamoDB table

  • Search for DynamoDB in the search bar and click on create table.

DynamoDB

  • Now enter the table name and enter the name of your primary key column [Note: If you enter a name for the sortkey then the combination of primary and sortkey will have to be unique].

Table creation

  • Select default settings under table settings and hit the create table button.

table settings dynamodb

  • Now you should see that the table is created, and you can feed in some data.

table created

fetching data from DynamoDB in our function

  • Let's replace the code from the previous code like this
const aws = require("aws-sdk")
const dynamo = new aws.DynamoDB.DocumentClient()

exports.handler = async (event) => {

    const studentID = event.pathParameters.studentID

    const data = await dynamo.get({
        TableName:"school",
        Key:{
            ID:studentID
        }
    }).promise()

    const response = {
        statusCode: 200,
        body: JSON.stringify(data),
    };
    return response;
};
  • let's review the code

  • By default the aws-sdk is installed in the instance running our function so we can use the DynamoDB client from there.

  • the get method on the document client takes an object as it's parameter where you specify the tablename and the key value to filter the data.

  • The get method requires a call back we are converting the call back into a promise by invoking the .promise() method.

  • if you deploy the code and try calling the api you'll get a internal server error to resolve it we have provide your function permission to access dynamodb.

  • So go to the configurations section in lambda and click on edit under the execution role card.

aws iam

  • Click on the view role name and it will take you the aws iam console.

view iam role

  • There you'll notice your iam user only has the permission for lambda now we can add a new permission by either attaching a new policy or creating an inline policy.

policy

  • under services choose DynamoDB

Image description

  • under actions choose what all can this user do with a table

op permission

  • For the sake of the post under resources select all resources but do not do this a production level project and click on review policy and then hit the create button.

res choose

  • Now try calling the api and it'll work

api response

Creating students

  • Now before you continue to the code provide DynamoDB write access to this function.

  • The below code allows us to create new entries in DynamoDB.

const aws = require("aws-sdk")
const dynamo = new aws.DynamoDB.DocumentClient()

exports.handler = async (event) => {
    const body = JSON.parse(event.body)
    console.log(body)

    const data = await dynamo.put({
        TableName:"school",
        Item:{
            ...body,
            ID: Math.floor(Math.random()*10000000).toString()
        }
    }).promise()


    const response = {
        statusCode: 200,
        body: JSON.stringify("Added new student welcome to the X-MEN"),
    };
    return response;
};
  • So here instead of get we are using the put method and we are extracting the data from the body of the request using event.body.

  • Now let's call the API using postman

Postman api call

  • Now if you go to the DynamoDB explore section you'll see that the new student has been added.

DynamoDB add data

Thanks for your time.