Amazon DynamoDB — Developing with AWS SDK to interact Serverless APIs

In this article, we are going to develop Amazon DynamoDB interactions with using AWS SDK.

We are going to do Amazon DynamoDB SDK Examples with using AWS SDK JavaScript v3 and use ES6 standards. By the end of the article, we will invoke DynamoDB API to perform database related tasks using the latest AWS SDK.

I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.

Amazon DynamoDB — Developing with AWS SDK

Amazon DynamoDB is a fully managed NoSQL cloud database that supports both document and key-value store models. You create schema-less tables for data without the need to provision or maintain dedicated database servers.

You can see the image at above, Basically we will develop NodeJS projects that are using SDK libraries in order to interact with Amazon DynamoDB.

The JavaScript API for DynamoDB is exposed through the DynamoDB, DynamoDB Streams, and DynamoDB.DocumentClient client classes. So SDK Libraries are using the DynamoDB APIs for interactions, we will see DynamoDB core APIs soon. But you can think that SDK libraries using the DynamoDB client classes, see Class: DynamoDB, Class: DynamoDBStreams, and Class: DynamoDB utility in the API Reference.

Lets talk about the topics that we will develop in this section:

  • Creating and using tables in DynamoDB
  • Reading and writing a single item in DynamoDB
  • Reading and writing items in batch in DynamoDB
  • Querying and scanning a DynamoDB table
  • PartiQL operations

In order to perform these operations with SDK, DynamoDB has package that we can see on Reference documents. Reference documents and need to use DynamoDB packages.

You can see Commands section of DynamoDB. Clients — Commands to interact with SDK packages.
As you remember that v3 has modularized structure and send commands with client objects.

This will reduce code size and increase lambda executions performance. As you can see that we have understood Amazon DynamoDB SDK libraries and start Developing with AWS SDK for Programmatic Access w/ Serverless APIs. But before that its good to understand DynamoDB APIs which APIs exposing from DynamoDB and which interactions can be held by SDK using DynamoDB core APIs.

Understanding DynamoDB Interactions — Working with Items and Attributes

Before we developing NodeJS lambda functions, We should understand the basics of DynamoDB, after that it will be very clear to interact with DynamoDB from our NodeJS lambda function. So the idea is that you should think DynamoDB as a AWS resource and DynamoDB expose awaitable APIs that we can call from our lambda function with using AWS SDK.

In Amazon DynamoDB, an item is a collection of attributes. Each attribute has a name and a value. An attribute value can be a scalar, a set, or a document type. For more information, see Amazon DynamoDB: How It Works. DynamoDB provides four operations for basic create, read, update, and delete (CRUD) functionality. All these operations are atomic.

  • PutItem — Create an item.
  • GetItem — Read an item.
  • UpdateItem — Update an item.
  • DeleteItem — Delete an item.

All these core interactions has a different core apis that we can find in the Amazon DynamoDB API Reference documentation. See the documentation, we have list of actions can be done for interacting DynamoDB. And all these core APIs can be invoke from using AWS CLI or using AWS SDK.

So after we have learned the basics of DynamoDB, how we can interact these methods from lambda function with using AWS SDK ? of course using with AWS SDK for JavaScript — Developer Guide for SDK Version 3.

Create NodeJS Project with DynamoDB SDK Packages

We are going to Create NodeJS Project with DynamoDB SDK Packages to interact with DynamoDB APIs. Open VS Code, create “dynamodb-sdk” folder. This will be our NodeJS project for this section.

Locate folder and run npm command in order to create package.json:

npm init -y

See and edit default package.json is created. The first thing we should do
Add “type”: “module”:

package.json 
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“type”: “module” — — — ADDED
}

this provide to use ES6 codes into nodejs projects. for example “import statements”.

Install required dynamodb sdk packages

Run command on package.json level

npm install @aws-sdk/client-dynamodb

See package installed in package.json file: “@aws-sdk/client-dynamodb”

{
“name”: “section8”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1"
},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“type”: “module”,
“dependencies”: {
@aws-sdk/client-dynamodb”: “³.87.0”
}
}

As you can see that node_modules are generated when running npm install command.

Create DynamoDBClient NodeJS Module For Connecting DynamoDB

This section we will interact with DynamoDB. For all these interactions we need to connect DynamoDB, for that purpose we should establish DynamoDBClient object. Instead of creating new client for every SDK request, its best practice to create NodeJS module and use this module for every particular SDK commands.

Create a libs directory, and create a Node.js module with the file name ddbClient.js. Copy and paste the code below into it, which creates the DynamoDB client object. Replace REGION with your AWS region.

// Create service client module using ES6 syntax.
import { DynamoDBClient } from “@aws-sdk/client-dynamodb”;
// Set the AWS Region.
const REGION = “us-east-2”; // Put your correct aws region
// Create an Amazon DynamoDB service client object.
const ddbClient = new DynamoDBClient({ region: REGION });
export { ddbClient };

As you can see that we have created NodeJS module for DynamoDB connections with creating a new instance of DynamoDBClient object. This client object will use every interaction with our SDK examples.

Now we are ready to develop our Topics:

  • Creating and using tables in DynamoDB
  • Reading and writing a single item in DynamoDB
  • Reading and writing items in batch in DynamoDB
  • Querying and scanning a DynamoDB table
  • PartiQL operations

Creating a DynamoDB Table

You can think this folder is our NodeJS project that interact with AWS resources using SDK libraries. And we will develop index.js like writing lambda functions. Be sure to configure the SDK as previously shown, including downloading the required clients and packages. To access DynamoDB, create a DynamoDB client service object. Create a JSON object containing the parameters needed to create a table, which in this example includes the name and data type for each attribute, the key schema, the name of the table, and the units of throughput to provision. Call the “CreateTableCommand” method of the DynamoDB service object.

We are going to design our table for e-commerce app:

order table
userName — PK
orderDate — SK

Now lets develop our codes:

// Import required AWS SDK clients and commands for Node.js
import { CreateTableCommand } from “@aws-sdk/client-dynamodb”;
import { ddbClient } from “../libs/ddbClient.js”;
// Set the parameters
export const params = {
AttributeDefinitions: [
{
AttributeName: “userName”,
AttributeType: “S”,
},
{
AttributeName: “orderDate”,
AttributeType: “S”,
}
],
KeySchema: [
{
AttributeName: “userName”,
KeyType: “HASH”,
},
{
AttributeName: “orderDate”,
KeyType: “RANGE”,
}
],
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1,
},
TableName: “order”,
StreamSpecification: {
StreamEnabled: false,
},
};

export const run = async () => {
try {
const data = await ddbClient.send(new CreateTableCommand(params));
console.log(“Table Created”, data);
return data;
} catch (err) {
console.log(“Error”, err);
}
};
run();

Run Code

PS C:\aws-serverless-bootcamp\section8\lecture57> node .\createtable.js

Result:

Table Created {
‘$metadata’: {
httpStatusCode: 200,
requestId: ‘7THJFICIAELLNHTH955NK4ANMJVV4KQNSO5AEMVJF66Q9ASUAAJG’,
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},

See that order table created as we developed with SDK. We use “CreateTableCommand” with passing required parameters, send DynamoDB via client object to perform operations.

Reading and writing a Single item in DynamoDB Table

We are going to Reading and writing a Single item in DynamoDB Table.

In this example, you use a series of Node.js modules to read and write one item in a DynamoDB table by using these methods of the DynamoDB client class:

  • PutItemCommand
  • UpdateItemCommand
  • GetItemCommand
  • DeleteItemCommand

Writing an Item into DynamoDB Table

To access DynamoDB, create a DynamoDB client service object. Create a JSON object containing the parameters needed to write item into tables. Call the PutItemCommand method of the DynamoDB service object.

// Import required AWS SDK clients and commands for Node.js
import { PutItemCommand } from “@aws-sdk/client-dynamodb”;
import { ddbClient } from “../libs/ddbClient.js”;
// Set the parameters
export const params = {
TableName: “product”,
Item: {
id: { N: “001” },
name: { S: “iphoneX” },
},
};
export const run = async () => {
try {
const data = await ddbClient.send(new PutItemCommand(params));
console.log(data);
return data;
} catch (err) {
console.error(err);
}
};
run();

To run the example, enter the following at the command prompt.
node writeitem.js

RESPONSE:
{
‘$metadata’: {
httpStatusCode: 200,
requestId: ‘3959BIFPPFNHK3M359N4POUJVNVV4KQNSO5AEMVJF66Q9ASUAAJG’,
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
LastEvaluatedTableName: undefined,
TableNames: [ ‘order’ ]
}

See that we have only 1 table — order. I am going to skip other commands but if you would like to continue, you can follow the below course.

Step by Step Design AWS Architectures w/ Course

I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.

In this course, we will learn almost all the AWS Serverless Services with all aspects. We are going to build serverless applications with using AWS Lambda, Amazon API Gateway, Amazon DynamoDB, Amazon Cognito, Amazon S3, Amazon SNS, Amazon SQS, Amazon EventBridge, AWS Step Functions, DynamoDB and Kinesis Streams. This course will be 100% hands-on, and you will be developing a real-world application with hands-on labs together and step by step.

Source Code

Get the Source Code from Serverless Microservices GitHub — Clone or fork this repository, if you like don’t forget the star. If you find or ask anything you can directly open issue on repository.

--

--

AWS Serverless with AWS Lambda, API Gateway, Amazon DynamoDB, Cognito, S3, SNS, SQS, EventBridge, Step Functions, DynamoDB and Kinesis Streams, CloudFormation, SAM, CDK. We will develop Lambda-based event-driven application integrate to all AWS Serverless Services.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mehmet Ozkaya

Software/Solutions Architect, Udemy Instructor, Working on Cloud-Native and Serverless Event-driven Microservices Architectures https://github.com/mehmetozkaya