Skip to content
Soroka Tech Blog

How to build Serverless API with database using AWS CDK

serverless, devops, aws, tutorial3 min read

Serverless gives us tremendous opportunities to ship new digital products faster at no cost in the beginning. The most classical way of using serverless is to have API backed by AWS Lambdas. This blog will guide the provision and deployment of an application using AWS CDK version 2. However, when I have started implementing it, issues started to appear. I would tell about them while depicting the process and code. Serverless will give the ability to have a full API setup for free.

First of all, what are we building? It will be an API Gateway backed by AWS Lambdas. They will be reading and writing items to the DynamoDB table. So, here we are, creating the CRUD with REST API. One can find the GitHub repository here

API Gateway -> AWS Lambda -> DynamoDB

Reading is great for many things. So our items will be books! The model will be like that:

2 "title": "name of the book>",
3 "author": "<author of the book>",
4 "yearPublished": "<published year of the book>",
5 "isbn": "<universal identifier of the book>"


In this demo application, we are using Dynamo DB. It is a NoSQL database where AWS manages infrastructure. It is working like a magic spell with the Lambda functions. This app will do classic CRUD operations.

1import { DocumentClient } from 'aws-sdk/clients/dynamodb';
2import { Book } from '../models/book';
3import uuid from 'uuid';
5const dynamo = new DocumentClient();
7export async function create(table: string, book: Book) {
8 const params = {
9 TableName: table,
10 Item: {
11 id: uuid.v4(),
13 }
14 }
15 const dbResponse = await dynamo.put(params).promise();
16 return params.Item;

The start will be related to the writing items to the table. Typescript allows having a strongly typed object. The only thing which will be great to have as unique as possible is UUID. In this case, getting a book by the ID will be straightforward. The deleting operation will be very similar.

1export async function get(table: string, id: string) {
2 const params = {
3 TableName: table,
4 Key: {
5 id
6 }
7 };
9 const dbResponse = await dynamo.get(params).promise();
10 return dbResponse.Item;
13export async function deleteItem(table: string, id: string) {
14 const params = {
15 TableName: table,
16 Key: {
17 id
18 }
19 }
20 await dynamo.delete(params).promise();

It would be great also to check the created items. Here I am using the 'Scan' operation, which goes through the whole table. For demo purposes, this should be enough. Whenever possible, one should use 'Query.'

1export async function list(table: string): Promise<DocumentClient.ItemList> {
2 const params = {
3 TableName: table,
4 }
5 const dbResponse = await dynamo.scan(params).promise();
6 if (dbResponse.Items) {
7 return dbResponse.Items;
8 }
9 throw new Error('Cannot get all books');

The most complicated request is to update the book from the database. It needs to have parameters and values to edit.

1export async function update(table: string, id: string, book: Book) {
2 const params = {
3 TableName: table,
4 Key: {
5 id,
6 },
7 ExpressionAttributeValues: {
8 ':title': book.title,
9 ':author':,
10 ':yearPublished': book.yearPublished,
11 ':isbn': book.isbn
12 },
13 UpdateExpression: 'SET title = :title, ' +
14 'author = :author, yearPublished = :yearPublished, isbn = :isbn',
15 ReturnValues: 'UPDATED_NEW',
16 }
17 await dynamo.update(params).promise();

Dependency injection is the first complication that is happening with lambdas. If one packs it to the AWS by using CDK or CloudFormation, there will be no dependencies. I am using typescript in the project, so in theory, running will create a working js file:

1npm i -D typescript
2tsc init

However, it is not so straightforward. There are two issues here:

  • packing additional files with functionality because having Lambda with the implementation inside one file is a bad practice
  • packing external dependencies. In our case, it will be UUID one.

I tried to pack just src/functions/create. Running Lambda will give that:

CloudWatch error

That is why the next logical step will be to find out how to pack Lambda code together with dependencies and don't upload 100 Mb of node_modules. I decided to use webpack for that. It does the job right and will allow running just this command after installation: webpack

Lambdas' main handler functions will be as simple as calling the DynamoDB file with the needed operations. For example, creating the item would be like that.

1import { APIGatewayProxyEventV2, Callback, Context } from 'aws-lambda';
2import { create } from '../connectors/dynamo-db-connector';
4export async function handler (event: APIGatewayProxyEventV2, context: Context, callback: Callback) {
5 if (typeof event.body === 'string') {
6 const bookItem = JSON.parse(event.body);
7 const createBook = await create(process.env.table as string, bookItem);
8 const response = {
9 statusCode: 201,
10 }
11 callback(null, response);
12 }
13 callback(null, {
14 statusCode: 400,
15 body: JSON.stringify('Request body is empty!')
16 });

One could find handlers for other operations in the repository.


As previously mentioned, CDK will be in charge of the infrastructure provisioning. I will be using just one stack with DynamoDB, 5 Lambdas, Rest API, permissions for table connections, and integrations for endpoints. We will put the infrastructure application in a separate folder <root>/infra.

To create DynamoDB with Lambda calling it, one will need ready-made typed constructs for DynamoDB, Lambda, and permissions. The code is situated one level above, so it is essential to put it like this. The good thing here is that CDK will error when one calls the template's 'synthesizing' with the wrong parameters. After that, Lambda will need a permission to put an item to DynamoDB. One could do this by adding one line of code.

1const dynamoTable = new ddb.Table(this, 'BookTable', {
2 tableName: 'BookStorage',
3 readCapacity: 1,
4 writeCapacity: 1,
5 partitionKey: {
6 name: 'id',
7 type: ddb.AttributeType.STRING,
8 },
11const createBookFunction = new lambda.Function(this, 'CreateHandler', {
12 runtime: lambda.Runtime.NODEJS_14_X,
13 code: lambda.Code.fromAsset('../code'),
14 handler: 'create.handler',
15 environment: {
16 table: dynamoTable.tableName
17 },
18 logRetention: RetentionDays.ONE_WEEK
21dynamoTable.grant(createBookFunction, 'dynamodb:PutItem')

After that, the function could be attached to the API. First, we are initializing RestAPI. Then, we add a resource to root for having a path like POST <api-root>/.

1const api = new apigw.RestApi(this, `BookAPI`, {
2 restApiName: `book-rest-api`,
5const mainPath = api.root.addResource('books');
7const createBookIntegration = new apigw.LambdaIntegration(createBookFunction);
9mainPath.addMethod('POST', createBookIntegration);

The steps shown in this section will be repeated for other endpoints also. The best part comes when one can see that lambda creation is the same but with different parameters. CDK could wrap it into the function for saving space and having reusable code for provisioning handlers.

Testing endpoints

After the manipulations mentioned in the previous sections, we can try out the API mentioned in this article. Let's start with the list of all books. The result should be empty.

1curl --location --request GET 'https://<api-id>.execute-api.<region>'
3Status: 200

After that, let's create a couple of books.

1curl --location --request POST 'https://<api-id>.execute-api.<region>' \
2--header 'Content-Type: application/json' \
3--data-raw '{
4"title": "Life of PI",
5"author": "Yann Martel",
6"yearPublished": "2000",
7"isbn": "0-676-97376-0"
11Status: 201

And one more:

1curl --location --request POST 'https://<api-id>.execute-api.<region>' \
2--header 'Content-Type: application/json' \
3--data-raw '{
4"title": "Simulacra and Simulation",
5"author": "Jean Baudrillard",
6"yearPublished": "0-472-06521-1",
7"isbn": "0-676-97376-0"
11Status: 201

Now we can call a list to make sure that all the books are in their places.

1curl --location --request GET 'https://<api-id>.execute-api.<region>'
4Status: 200
6 "isbn": "0-676-97376-0",
7 "id": "617d6b3e-ce6d-4e8d-a10f-05d6703ad7ac",
8 "yearPublished": "2000",
9 "title": "Life of PI",
10 "author": "Yann Martel"
11}, {
12 "isbn": "0-676-97376-0",
13 "id": "2a8251ee-73ee-4717-8f6f-0f11dd2b861f",
14 "yearPublished": "0-472-06521-1",
15 "title": "Simulacra and Simulation",
16 "author": "Jean Baudrillard"

Lambda added the books, and a listing is also working. However, there is an error in the database. I noticed that 'Life of PI' was published in 2001 and not in 2000. So, we need to call the update endpoint.

1curl --location --request PUT '' \
2--header 'Content-Type: application/json' \
3--data-raw '{
4 "isbn": "0-676-97376-0",
5 "yearPublished": "2001",
6 "title": "Life of PI",
7 "author": "Yann Martel"
10Status: 200

Another list call will show that the book was successfully updated.

2 "isbn": "0-676-97376-0",
3 "id": "617d6b3e-ce6d-4e8d-a10f-05d6703ad7ac",
4 "yearPublished": "2001",
5 "author": "Yann Martel",
6 "title": "Life of PI"
7}, {
8 "isbn": "0-676-97376-0",
9 "id": "2a8251ee-73ee-4717-8f6f-0f11dd2b861f",
10 "yearPublished": "0-472-06521-1",
11 "title": "Simulacra and Simulation",
12 "author": "Jean Baudrillard"

Let's delete one of the books by calling the DELETE endpoint.

1curl --location --request DELETE 'https://<api-id>.execute-api.<region>'
2Status: 200

After calling it multiple times with different ids, one will get empty response for the list of books. This is what we are expecting here.

In this article, I showed how to deploy Serverless API with the NoSQL Database using AWS Lambda, DynamoDB, and API Gateway deployed by CDK. Lambdas have all permissions for CRUD operations. This can be a sample project for a more complicated setup. Also, I was using the webpack to have all the node dependencies in place. The future work will include the CodePipeline for CI/CD connected to the GitHub hook. Thanks for reading this article! 

This is Part 1 for the Series related to Serverless API. Part 2 focuses on deployment that can be found here

© 2022 by Soroka Tech Blog. All rights reserved.
Theme by LekoArts