How to build a CRUD API on Amazon DynamoDB
Model data and implement CRUD operations on Amazon DynamoDB from Node.js with the AWS SDK v3. Covers key design, on-demand tables, and index queries.
Amazon DynamoDB is a fully managed NoSQL key-value and document database with single-digit millisecond latency at any scale. Unlike relational databases, you design access patterns first, then a key schema that serves them. This tutorial builds a CRUD layer in Node.js with the AWS SDK v3.
Prerequisites
- An AWS account and Node.js 20.
@aws-sdk/client-dynamodband@aws-sdk/lib-dynamodbinstalled.
Steps
1. Design the key schema
For an orders service keyed by customer, use a partition key pk (CUSTOMER#123) and sort key sk (ORDER#2026-01-01). This groups a customer's orders together for efficient queries.
2. Create the table
aws dynamodb create-table --table-name orders \
--attribute-definitions AttributeName=pk,AttributeType=S AttributeName=sk,AttributeType=S \
--key-schema AttributeName=pk,KeyType=HASH AttributeName=sk,KeyType=RANGE \
--billing-mode PAY_PER_REQUEST
On-demand billing avoids capacity planning.
3. Put and get items
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, GetCommand } from "@aws-sdk/lib-dynamodb";
const doc = DynamoDBDocumentClient.from(new DynamoDBClient({}));
await doc.send(new PutCommand({ TableName: "orders", Item: { pk: "CUSTOMER#123", sk: "ORDER#1", total: 42 } }));
const { Item } = await doc.send(new GetCommand({ TableName: "orders", Key: { pk: "CUSTOMER#123", sk: "ORDER#1" } }));
4. Update items
import { UpdateCommand } from "@aws-sdk/lib-dynamodb";
await doc.send(new UpdateCommand({
TableName: "orders", Key: { pk: "CUSTOMER#123", sk: "ORDER#1" },
UpdateExpression: "SET #t = :t", ExpressionAttributeNames: { "#t": "total" }, ExpressionAttributeValues: { ":t": 50 }
}));
5. Delete items
import { DeleteCommand } from "@aws-sdk/lib-dynamodb";
await doc.send(new DeleteCommand({ TableName: "orders", Key: { pk: "CUSTOMER#123", sk: "ORDER#1" } }));
6. Query an index
Fetch all of a customer's orders with a Query on the partition key, or add a Global Secondary Index to query by another attribute such as status.
Verification
Run each operation and confirm the returned items. Use aws dynamodb scan --table-name orders during development to inspect contents (avoid scans in production). Confirm a query returns only the targeted partition.
Next Steps
Add optimistic locking with condition expressions, enable point-in-time recovery, and stream changes to Lambda with DynamoDB Streams.