Lambda functions with DynamoDB & Node
Tags: serverless, beginners, aws, dynamodb
Published: 2022-11-12 15:51:13

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1vpppwai7l6s5auv8uq5.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ree4tdls796ak9gy2p04.png)

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

![table settings dynamodb](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o3ca1na1xoqytql3jcn6.png)

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

![table created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4exrusjxqq2nzt2dh5va.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2q8v5wl2itswdz0vwfxr.png)
- Click on the view role name and it will take you the aws iam console.

![view iam role](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6uzrv8mxr2nzla4npmws.png)

-  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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2a8c9nn2qk55m2740jtl.png)

- under services choose DynamoDB

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1iewyci0fen8lbaahqet.png)

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


![op permission](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tt3amd3pt4vlnikhsgid.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/geujcsyzx1bjlrk1xxqw.png)

- Now try calling the api and it'll work


![api response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i92cay1ebjs4goipcwa8.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5gbaktekr792ibui02li.png)

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

![DynamoDB add data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zj1nur6o2y8629lpucdt.png)

Thanks for your time.