What you’ll build
You will build a small API with two routes. One route stores an item in a DynamoDB table. The other lists the items for one partition key. The Serverless Framework defines the table, the functions and the permissions in a single serverless.yml file, and deploys them as a CloudFormation stack.
Before you start
- An AWS account and an IAM user with permission to deploy CloudFormation, Lambda, API Gateway, IAM roles and DynamoDB tables.
- Node.js (current LTS) and npm on your computer.
- The Serverless Framework CLI. Install it with
npm install -g serverless.
Serverless Framework v4 asks you to sign in to a Serverless account the first time you use it. Check its current licensing terms, because they differ for individuals and for larger organizations.
Step 1: Create a Serverless Framework service
Create a service from the Node.js template:
serverless create --template aws-nodejs --path dynamodb-serverless
cd dynamodb-serverless
The template creates a handler.js file and a serverless.yml file. Replace the contents of serverless.yml with the next step.
Step 2: Define the table, the permissions and the functions
Replace serverless.yml with this file. It sets the runtime and the table name, grants the functions access to the table, defines two HTTP routes, and defines the table with a partition key (pk) and a sort key (sk):
service: dynamodb-serverless
provider:
name: aws
runtime: nodejs24.x
region: us-east-1
environment:
TABLE_NAME:
Ref: ItemsTable
iam:
role:
statements:
- Effect: Allow
Action:
- dynamodb:PutItem
- dynamodb:Query
Resource:
- Fn::GetAtt: [ItemsTable, Arn]
functions:
createItem:
handler: handler.createItem
events:
- httpApi: 'POST /items'
listItems:
handler: handler.listItems
events:
- httpApi: 'GET /items/{pk}'
resources:
Resources:
ItemsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: items-${sls:stage}
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: pk
AttributeType: S
- AttributeName: sk
AttributeType: S
KeySchema:
- AttributeName: pk
KeyType: HASH
- AttributeName: sk
KeyType: RANGE
A few details to note:
- Permissions. The policy lists
PutItemandQueryonly, and it is scoped to this table’s ARN. AddGetItemorDeleteItemif you extend the example. Avoiddynamodb:*on all resources, which grants far more access than the functions need. - Billing.
BillingMode: PAY_PER_REQUESTis on-demand capacity. You do not set read or write capacity units. - Keys. Only the key attributes appear in
AttributeDefinitions. Other attributes can differ from item to item. - Runtime. Use a Node.js runtime that AWS currently supports. The console and the Lambda documentation list the current versions, so update
nodejs24.xif it has moved on.
Step 3: Write the functions with the AWS SDK v3
Node.js 18 and newer Lambda runtimes include AWS SDK v3, so you do not need to bundle the SDK. Replace handler.js with this code:
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const {
DynamoDBDocumentClient,
PutCommand,
QueryCommand,
} = require("@aws-sdk/lib-dynamodb");
const client = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const TABLE_NAME = process.env.TABLE_NAME;
exports.createItem = async (event) => {
const item = JSON.parse(event.body || "{}");
if (!item.pk || !item.sk) {
return { statusCode: 400, body: JSON.stringify({ error: "pk and sk are required" }) };
}
await client.send(new PutCommand({ TableName: TABLE_NAME, Item: item }));
return { statusCode: 201, body: JSON.stringify(item) };
};
exports.listItems = async (event) => {
const result = await client.send(
new QueryCommand({
TableName: TABLE_NAME,
KeyConditionExpression: "#pk = :pk",
ExpressionAttributeNames: { "#pk": "pk" },
ExpressionAttributeValues: { ":pk": event.pathParameters.pk },
})
);
return { statusCode: 200, body: JSON.stringify(result.Items) };
};
The listItems function uses QueryCommand, which reads only the items with the matching partition key. The code uses #pk as an expression attribute name to avoid any clash with reserved words.
Step 4: Deploy and test
Deploy the service:
serverless deploy
The output includes the base URL of the HTTP API. Create an item, then list the items for its partition key. Replace <api-url> with the URL from the output:
curl -X POST <api-url>/items \
-H "Content-Type: application/json" \
-d '{"pk": "user#42", "sk": "order#1001", "total": 25}'
curl <api-url>/items/user%2342
The second command returns a JSON array with the item you created. The # in the partition key is URL-encoded as %23.
Query vs. scan: why the key design matters
A Scan reads every item in the table and then filters the results. A Query reads only the items with one partition key value. On a small table you may not notice the difference, but on a large table a scan reads far more data, takes longer and costs more.
Design the keys around the questions your app asks. If you need “all orders for a user,” make the user the partition key and the order ID the sort key. Then a Query answers the question directly. Use GetItem when you know the full primary key.
DynamoDB limits an item to 400 KB. Query and scan return at most 1 MB of data per call, so use the LastEvaluatedKey value in the response to fetch the next page.
Costs and capacity modes
With on-demand capacity (PAY_PER_REQUEST), you pay per read and write request. The price per million requests in us-east-1 is low, but it still adds up for high-traffic workloads. Provisioned capacity bills for reserved read and write capacity units instead. It can be cheaper for steady traffic, but you must size it. DynamoDB’s free tier includes some provisioned capacity, so check the current allowance on the pricing page.
The API Gateway HTTP API used here (httpApi) costs less per million requests than the older REST API (http). Lambda and API Gateway also charge for usage, so check your bill after testing.
Troubleshooting
AccessDeniedExceptionfrom DynamoDB. The function’s role is missing an action or points at the wrong table ARN. Check theiamblock inserverless.yml.ResourceNotFoundException. TheTABLE_NAMEenvironment variable is empty or wrong. Check the function’s configuration in the Lambda console.- The deploy fails with a name clash. Table names must be unique within an account and Region. Change
items-${sls:stage}to a unique name. Cannot find module '@aws-sdk/client-dynamodb'when running locally. The code runs in Lambda, where the SDK is included. Local testing needs the packages installed withnpm install, or use a local DynamoDB emulator.
Clean up (and the data-loss warning)
serverless remove deletes the CloudFormation stack, and that includes the table and all of its data. If you want to keep the table after removing the stack, set DeletionPolicy: Retain on ItemsTable. Back up any data you care about before you run the command.
serverless remove
Then check the DynamoDB console to confirm that the table is gone, and remove any log groups the functions left behind.
Next steps
- Add a function that reads a single item with
GetItem. - Write the same kind of function in Java with the Spring Boot on Lambda tutorial.
- Learn the Lambda basics in the create a Lambda function in Python guide.
- Check the guide to avoiding unexpected AWS charges for the billing alerts to set up first.