How to create a CRUD API with serverless using DynamoDB
In this example we will look at how to create a CRUD API with serverless using DynamoDB. We’ll be using SST. Our API will be creating, reading, updating, and deleting notes.
Requirements
- Node.js 16 or later
- We’ll be using TypeScript
- An AWS account with the AWS CLI configured locally
Create an SST app
Let’s start by creating an SST app.
$ npx create-sst@latest --template=base/example crud-api-dynamodb
$ cd crud-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: "crud-api-dynamodb",
region: "us-east-1",
};
},
} satisfies SSTConfig;
Project layout
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, 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.
Adding DynamoDB
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.
Replace the stacks/ExampleStack.ts
with the following.
import { Api, StackContext, Table } from "sst/constructs";
export function ExampleStack({ stack }: StackContext) {
// Create the table
const table = new Table(stack, "Notes", {
fields: {
userId: "string",
noteId: "string",
},
primaryIndex: { partitionKey: "userId", sortKey: "noteId" },
});
}
This creates a serverless DynamoDB table using Table
. Our table is going to look something like this:
userId | noteId | content | createdAt |
---|---|---|---|
123 | 1 | Hi! | Feb 5 |
Setting up our routes
Now let’s add the API.
Add this after 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: {
"GET /notes": "packages/functions/src/list.main",
"POST /notes": "packages/functions/src/create.main",
"GET /notes/{id}": "packages/functions/src/get.main",
"PUT /notes/{id}": "packages/functions/src/update.main",
"DELETE /notes/{id}": "packages/functions/src/delete.main",
},
});
// Show the API endpoint in the output
stack.addOutputs({
ApiEndpoint: api.url,
});
We are creating an API here using the Api
construct. And we are adding five routes to it.
GET /notes
POST /notes
GET /notes/{id}
PUT /notes/{id}
DELETE /notes/{id}
These will be getting a list of notes, creating a note, getting, updating, and deleting a specific note respectively.
We’ll also bind our table to our API. It allows our API to access (read and write) the table we just created.
Create a note
Let’s turn towards the functions that’ll be powering our API. Starting with the one that creates our note.
Add the following to packages/functions/src/create.ts
.
import * as uuid from "uuid";
import { DynamoDB } from "aws-sdk";
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
import { Table } from "sst/node/table";
const dynamoDb = new DynamoDB.DocumentClient();
export const main: APIGatewayProxyHandlerV2 = async (event) => {
const data = JSON.parse(event.body);
const params = {
// Get the table name from the environment variable
TableName: Table.Notes.tableName,
Item: {
userId: "123",
noteId: uuid.v1(), // A unique uuid
content: data.content, // Parsed from request body
createdAt: Date.now(),
},
};
await dynamoDb.put(params).promise();
return {
statusCode: 200,
body: JSON.stringify(params.Item),
};
};
Here we are creating a new row in our DynamoDB table. First we JSON parse the request body. That gives us the content of the note. Then we are hard coding the userId
to 123
for now. Our API will not be tied to a user. We’ll tackle that in a later example. We are also using a uuid
package to generate a unique noteId
.
Let’s install both the packages we are using here.
Run the below command in the packages/functions/
folder.
$ npm install aws-sdk uuid
Read the list of notes
Next, let’s write the function that’ll fetch all our notes.
Add the following to packages/functions/src/list.ts
.
import { DynamoDB } from "aws-sdk";
import { Table } from "sst/node/table";
const dynamoDb = new DynamoDB.DocumentClient();
export async function main() {
const params = {
// Get the table name from the environment variable
TableName: Table.Notes.tableName,
// Get all the rows where the userId is our hardcoded user id
KeyConditionExpression: "userId = :userId",
ExpressionAttributeValues: {
":userId": "123",
},
};
const results = await dynamoDb.query(params).promise();
return {
statusCode: 200,
body: JSON.stringify(results.Items),
};
}
Here we are getting all the notes for our hard coded userId
, 123
.
Read a specific note
We’ll do something similar for the function that gets a single note.
Create a packages/functions/src/get.ts
.
import { DynamoDB } from "aws-sdk";
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
import { Table } from "sst/node/table";
const dynamoDb = new DynamoDB.DocumentClient();
export const main: APIGatewayProxyHandlerV2 = async (event) => {
const params = {
// Get the table name from the environment variable
TableName: Table.Notes.tableName,
// Get the row where the noteId is the one in the path
Key: {
userId: "123",
noteId: event.pathParameters.id,
},
};
const results = await dynamoDb.get(params).promise();
return {
statusCode: 200,
body: JSON.stringify(results.Item),
};
};
We are getting the note with the id that’s passed in through the API endpoint path. The event.pathParameters.id
corresponds to the id in /notes/{id}
.
Update a note
Now let’s update our notes.
Add a packages/functions/src/update.ts
with:
import { DynamoDB } from "aws-sdk";
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
import { Table } from "sst/node/table";
const dynamoDb = new DynamoDB.DocumentClient();
export const main: APIGatewayProxyHandlerV2 = async (event) => {
const data = JSON.parse(event.body);
const params = {
// Get the table name from the environment variable
TableName: Table.Notes.tableName,
// Get the row where the noteId is the one in the path
Key: {
userId: "123",
noteId: event.pathParameters.id,
},
// Update the "content" column with the one passed in
UpdateExpression: "SET content = :content",
ExpressionAttributeValues: {
":content": data.content || null,
},
ReturnValues: "ALL_NEW",
};
const results = await dynamoDb.update(params).promise();
return {
statusCode: 200,
body: JSON.stringify(results.Attributes),
};
};
We are first JSON parsing the request body. We use the content we get from it, to update the note. The ALL_NEW
property means that this update call will return the updated row.
Delete a note
To complete the CRUD operations, let’s delete the note.
Add this to packages/functions/src/delete.ts
.
import { DynamoDB } from "aws-sdk";
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
import { Table } from "sst/node/table";
const dynamoDb = new DynamoDB.DocumentClient();
export const main: APIGatewayProxyHandlerV2 = async (event) => {
const params = {
// Get the table name from the environment variable
TableName: Table.Notes.tableName,
// Get the row where the noteId is the one in the path
Key: {
userId: "123",
noteId: event.pathParameters.id,
},
};
await dynamoDb.delete(params).promise();
return {
statusCode: 200,
body: JSON.stringify({ status: true }),
};
};
Now let’s test what we’ve created so far.
Starting your dev environment
SST features a 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://t34witddz7.execute-api.us-east-1.amazoncom
The ApiEndpoint
is the API we just created.
Let’s test our endpoint using the integrated SST Console. The SST Console is a web based dashboard to manage your SST apps Learn more about it in our docs.
Let’s create our first note, go to the API explorer and click on the POST /notes
route.
Note, The API explorer 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.
In the Headers tab enter Content-type
in Header 1 input and application/json
in Value 1 input. Go to the Body tab and paste the below json.
{ "content": "Hello World" }
Now, hit the Send button to send the request.
This should create a new note.
To retrieve the created note, go to GET /notes/{id}
route and in the URL tab enter the id of the note we created in the id field and click the Send button to get that note.
Also let’s go to the DynamoDB tab in the SST Console and check that the value has been created in the table.
Note, The DynamoDB explorer allows you to query the DynamoDB tables in the Table
constructs in your app. You can scan the table, query specific keys, create and edit items.
Now to update our note, we need to make a PUT
request, go to PUT /notes/{id}
route.
In the URL tab, enter the id of the note we created and in the body tab and enter the below json value and hit Send.
{ "content": "Updating the note" }
This should respond with the updated note.
Click the Send button of the GET /notes
route to get a list of notes.
You should see the list of notes.
To delete a note, go to the DELETE /notes/{id}
and enter the id of the note to delete in the URL tab and hot Send.
Making changes
Let’s make a quick change to test our Live Lambda Development environment. We want our get
function to return an error if it cannot find the note.
Replace the return
statement in packages/functions/src/gets.ts
with:
return results.Item
? {
statusCode: 200,
body: JSON.stringify(results.Item),
}
: {
statusCode: 404,
body: JSON.stringify({ error: true }),
};
Now let’s send an invalid request by entering a random note id which is not present in the table.
You should see an error being printed out.
Deploying to prod
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 app for our users.
Once deployed, you should see something like this.
✅ prod-rest-api-dynamodb-ExampleStack
Stack prod-rest-api-dynamodb-ExampleStack
Status: deployed
Outputs:
ApiEndpoint: https://ck198mfop1.execute-api.us-east-1.amazoncom
Run the below command to open the SST Console in prod stage to test the production endpoint.
npx sst console --stage prod
Go to the API explorer and click Send button of the GET /notes
route, to send a GET
request.
Cleaning up
Finally, you can remove the resources created in this example using the following commands.
$ npx sst remove
$ npx sst remove --stage prod
Conclusion
And that’s it! We’ve got a completely serverless CRUD API. In another example, we’ll add authentication to our API, so we can fetch the notes for a given user. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!
Example repo for reference
github.com/sst/sst/tree/master/examples/crud-api-dynamodbFor help and discussion
Comments on this exampleMore Examples
APIs
-
REST API
Building a simple REST API.
-
WebSocket API
Building a simple WebSocket API.
-
Go REST API
Building a REST API with Golang.
-
Custom Domains
Using a custom domain in an API.
Web Apps
-
React.js
Full-stack React app with a serverless API.
-
Next.js
Full-stack Next.js app with DynamoDB.
-
Vue.js
Full-stack Vue.js app with a serverless API.
-
Svelte
Full-stack SvelteKit app with a serverless API.
-
Gatsby
Full-stack Gatsby app with a serverless API.
-
Angular
Full-stack Angular app with a serverless API.
Mobile Apps
GraphQL
Databases
-
DynamoDB
Using DynamoDB in a serverless API.
-
MongoDB Atlas
Using MongoDB Atlas in a serverless API.
-
PostgreSQL
Using PostgreSQL and Aurora in a serverless API.
-
PlanetScale
Using PlanetScale in a serverless API.
Authentication
Using SST Auth
-
Facebook Auth
Adding Facebook auth to a full-stack serverless app.
-
Google Auth
Adding Google auth to a full-stack serverless app.
Using Cognito Identity Pools
-
Cognito IAM
Authenticating with Cognito User Pool and Identity Pool.
-
Facebook Auth
Authenticating a serverless API with Facebook.
-
Twitter Auth
Authenticating a serverless API with Twitter.
-
Auth0 IAM
Authenticating a serverless API with Auth0.
Using Cognito User Pools
-
Cognito JWT
Adding JWT authentication with Cognito.
-
Auth0 JWT
Adding JWT authentication with Auth0.
-
Google Auth
Authenticating a full-stack serverless app with Google.
-
GitHub Auth
Authenticating a full-stack serverless app with GitHub.
-
Facebook Auth
Authenticating a full-stack serverless app with Facebook.
Async Tasks
-
Cron
A simple serverless Cron job.
-
Queues
A simple queue system with SQS.
-
Pub/Sub
A simple pub/sub system with SNS.
-
Resize Images
Automatically resize images uploaded to S3.
-
Kinesis data streams
A simple Kinesis Data Stream system.
-
EventBus
A simple EventBridge system with EventBus.
Editors
-
Debug With VS Code
Using VS Code to debug serverless apps.
-
Debug With WebStorm
Using WebStorm to debug serverless apps.
-
Debug With IntelliJ
Using IntelliJ IDEA to debug serverless apps.
Monitoring
Miscellaneous
-
Lambda Layers
Using the @sparticuz/chromium layer to take screenshots.
-
Middy Validator
Use Middy to validate API request and responses.