layout | title | short_title | date | lang | index | type | description | short_desc | repo | ref | comments_id |
---|---|---|---|---|---|---|---|---|---|---|---|
example |
How to use DynamoDB in your serverless app |
DynamoDB |
2021-02-03 16:00:00 -0800 |
en |
1 |
database |
In this example we will look at how to use DynamoDB in your serverless app on AWS using SST. We'll be using the Api and Table constructs to create a simple hit counter. |
Using DynamoDB in a serverless API. |
rest-api-dynamodb |
how-to-use-dynamodb-in-your-serverless-app |
how-to-use-dynamodb-in-your-serverless-app/2307 |
In this example we will look at how to use DynamoDB in our serverless app using [SST]({{ site.sst_github_repo }}). We'll be creating a simple hit counter.
- Node.js 16 or later
- We'll be using TypeScript
- An [AWS account]({% link _chapters/create-an-aws-account.md %}) with the [AWS CLI configured locally]({% link _chapters/configure-the-aws-cli.md %})
{%change%} Let's start by creating an SST app.
$ npx create-sst@latest --template=base/example rest-api-dynamodb
$ cd rest-api-dynamodb
$ npm install
By default, our app will be deployed to the us-east-1
AWS region. This can be changed in the sst.config.ts
in your project root.
import { SSTConfig } from "sst";
export default {
config(_input) {
return {
name: "rest-api-dynamodb",
region: "us-east-1",
};
},
} satisfies SSTConfig;
An SST app is made up of two parts.
-
stacks/
— App InfrastructureThe code that describes the infrastructure of your serverless app is placed in the
stacks/
directory of your project. SST uses [AWS CDK]({% link _archives/what-is-aws-cdk.md %}), to create the infrastructure. -
packages/functions/
— App CodeThe code that's run when your API is invoked is placed in the
packages/functions/
directory of your project.
Amazon DynamoDB is a reliable and highly-performant NoSQL database that can be configured as a true serverless database. Meaning that it'll scale up and down automatically. And you won't get charged if you are not using it.
{%change%} Replace the stacks/ExampleStack.ts
with the following.
import { Api, ReactStaticSite, StackContext, Table } from "sst/constructs";
export function ExampleStack({ stack }: StackContext) {
// Create the table
const table = new Table(stack, "Counter", {
fields: {
counter: "string",
},
primaryIndex: { partitionKey: "counter" },
});
}
This creates a serverless DynamoDB table using [Table
]({{ site.v2_url }}/constructs/Table). It has a primary key called counter
. Our table is going to look something like this:
counter | tally |
---|---|
hits | 123 |
Now let's add the API.
{%change%} Add this below the Table
definition in stacks/ExampleStack.ts
.
// Create the HTTP API
const api = new Api(stack, "Api", {
defaults: {
function: {
// Bind the table name to our API
bind: [table],
},
},
routes: {
"POST /": "packages/functions/src/lambda.main",
},
});
// Show the URLs in the output
stack.addOutputs({
ApiEndpoint: api.url,
});
Our [API]({{ site.v2_url }}/constructs/api) simply has one endpoint (the root). When we make a POST
request to this endpoint the Lambda function called main
in packages/functions/src/lambda.ts
will get invoked.
We'll also bind our table to our API. It allows our API to access (read and write) the table we just created.
Now in our function, we'll start by reading from our DynamoDB table.
{%change%} Replace packages/functions/src/lambda.ts
with the following.
import { DynamoDB } from "aws-sdk";
import { Table } from "sst/node/table";
const dynamoDb = new DynamoDB.DocumentClient();
export async function main() {
const getParams = {
// Get the table name from the environment variable
TableName: Table.Counter.tableName,
// Get the row where the counter is called "hits"
Key: {
counter: "hits",
},
};
const results = await dynamoDb.get(getParams).promise();
// If there is a row, then get the value of the
// column called "tally"
let count = results.Item ? results.Item.tally : 0;
return {
statusCode: 200,
body: count,
};
}
We make a get
call to our DynamoDB table and get the value of a row where the counter
column has the value hits
. Since, we haven't written to this column yet, we are going to just return 0
.
{%change%} Let's install the aws-sdk
package in the packages/functions/
folder.
$ npm install aws-sdk
And let's test what we have so far.
{%change%} SST features a [Live Lambda Development]({{ site.v2_url }}/live-lambda-development) environment that allows you to work on your serverless apps live.
$ npm run dev
The first time you run this command it'll take a couple of minutes to deploy your app and a debug stack to power the Live Lambda Development environment.
===============
Deploying app
===============
Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-rest-api-dynamodb-ExampleStack: deploying...
✅ dev-rest-api-dynamodb-ExampleStack
Stack dev-rest-api-dynamodb-ExampleStack
Status: deployed
Outputs:
ApiEndpoint: https://u3nnmgdigh.execute-api.us-east-1.amazonaws.com
The ApiEndpoint
is the API we just created.
Let's test our endpoint with the SST Console. The SST Console is a web based dashboard to manage your SST apps. [Learn more about it in our docs]({{ site.v2_url }}/console).
Go to the API tab and click Send button to send a POST
request.
Note, The [API explorer]({{ site.v2_url }}/console#api) lets you make HTTP requests to any of the routes in your Api
construct. Set the headers, query params, request body, and view the function logs with the response.
You should see a 0
in the response body.
Now let's update our table with the hits.
{%change%} Add this above the return
statement in packages/functions/src/lambda.ts
.
const putParams = {
TableName: Table.Counter.tableName,
Key: {
counter: "hits",
},
// Update the "tally" column
UpdateExpression: "SET tally = :count",
ExpressionAttributeValues: {
// Increase the count
":count": ++count,
},
};
await dynamoDb.update(putParams).promise();
Here we are updating the clicks
row's tally
column with the increased count.
And if you head over to your API explorer and hit the Send button again, you should see the count increase!
Also let's go to the DynamoDB tab in the SST Console and check that the value has been updated in the table.
Note, The [DynamoDB explorer]({{ site.v2_url }}/console#dynamodb) allows you to query the DynamoDB tables in the [Table
]({{ site.v2_url }}/constructs/Table) constructs in your app. You can scan the table, query specific keys, create and edit items.
{%change%} To wrap things up we'll deploy our app to prod.
$ npx sst deploy --stage prod
This allows us to separate our environments, so when we are working in dev
, it doesn't break the API for our users.
Finally, you can remove the resources created in this example using the following commands.
$ npx sst remove
$ npx sst remove --stage prod
And that's it! We've got a completely serverless hit counter. In another example, [we'll expand on this to create a CRUD API]({% link _examples/how-to-create-a-crud-api-with-serverless-using-dynamodb.md %}). Check out the repo below for the code we used in this example. And leave a comment if you have any questions!