How to create a REST API in Java using DynamoDB and Serverless
Tags: java, dynamodb, serverless, restapi
Published: 2022-04-11 22:39:50

Originally posted at [Serverless](https://www.serverless.com/blog/how-to-create-a-rest-api-in-java-using-dynamodb-and-serverless)

In this walkthrough, we will build a products-api serverless service that will implement a REST API for products. We will be using Java as our language of choice. The data will be stored in a [DynamoDB](https://serverless.com/dynamodb/) table, and the service will be deployed to AWS.

![](https://cdn-images-1.medium.com/max/2000/0*qJ7dsbx_iQM_ByXu.png)

What we will cover:

* Pre-requisites

* Creating the REST API service

* Deep dive into the Java code

* Deploying the service

* Calling the API

## Install Pre-requisites

Before we begin, you’ll need the following:

* Install node and npm

* Install the [Serverless Framework installed](https://serverless.com/framework/docs/providers/aws/guide/quick-start/) with an AWS account set up.

* Install [Oracle JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html) and NOT Java JRE. Set the following: export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home

* Install [Apache Maven](https://maven.apache.org/). After [downloading](https://maven.apache.org/download.html) and [installing](https://maven.apache.org/install.html) Apache Maven, add the apache-maven-x.x.x folder to the PATH environment variable.

## Testing Pre-requisites

Test Java installation:
{% gist https://gist.github.com/richardgrantserverless/98d384d9c0285146c2a8394b14cc24e1.js %}
Test Maven installation:
{% gist https://gist.github.com/richardgrantserverless/271ff2545f6e8be22e1c049c52806b2d.js %}
## Create the Serverless project

Let’s create a project named products-api, using the aws-java-maven boilerplate template provided by the [Serverless Framework](https://serverless.com/framework/), as shown below:
{% gist https://gist.github.com/richardgrantserverless/efc78d1970c3d010466198b2d93b4d86.js %}
## Updating the project

The serverless boilerplate template aws-java-maven gives us a nice starting point and builds a fully functional service using Java and Maven. However, we'll need to adapt it to our Products API service that we are building.

Let’s update the project hello to products-api in the POM i.e. pom.xml:
{% gist https://gist.github.com/richardgrantserverless/4e976b3ac251ea58cfe04bc94a0d6c48.js %}
## The serverless.yml

Let’s add the relevant Lambda handlers under functions and update the deployment artifact under package, as per our project requirements.

Update the following sections:
{% gist https://gist.github.com/richardgrantserverless/3d606382593f1d173bb973187ab0ae92.js %}
## Managing the DynamoDB table

Since we will be using a DynamoDB table to store our products data, we will let the Serverless Framework manage the DynamoDB resource and the relevant IAM Role permissions for the lambda functions to access the DynamoDB table.

Add the following section for iamRoleStatements under the provider section in the serverless.yml file:
{% gist https://gist.github.com/richardgrantserverless/79af5a76bec65de87d630b5f97700f2a.js %}
Now, to create and manage the DynamoDB table from within our serverless project, we can add a resources section to our serverless.yml file. This section describes the DynamoDB resource via a CloudFormation syntax:
{% gist https://gist.github.com/richardgrantserverless/266101b2db36777ad10c857c3ba49dfd.js %}
## The DynamoDB Adapter

We will create an adapter whose responsibility will be to manage the connection to the specifed DynamoDB table using configuration, like the AWS region where the table will be deployed. The DynamoDB adapter class is a singleton that instantiates a AmazonDynamoDB client and a [AWS DBMapper](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.Methods.html) class.

Here’s an excerpt from the DynamoDBAdapter class:
{% gist https://gist.github.com/richardgrantserverless/bad4f07c3614ecb15075afc403556a11.js %}
## The Product POJO

We have the Product [POJO](https://en.wikipedia.org/wiki/Plain_old_Java_object) that represents the Product entity and encapsulates all its functionality in a class. The Product POJO class defines a data structure that matches the DynamoDB table schema and provides helper methods for easy management of product data.
>  *The AWS SDK provides an easy way to annotate a POJO with DynamoDB specific attributes as defined by [Java Annotations for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.Annotations.html)*

We annotate the Product POJO class with:

* a DynamoDBTable attribute to specify the DynamoDB table name

* a DynamoDBHashKey attribute to map a property to a DynamoDB Haskey

* a DynamoDBRangeKey attribute to map a property to a DynamoDB RangeKey

* a DynamoDBAutoGeneratedKey attribute to map a property that needs to get a auto-generated id

Also, note that we get the product table name from a environment variable PRODUCTS_TABLE_NAME defined in our serverless.yml file:
{% gist https://gist.github.com/richardgrantserverless/7b190c8ff4e8e474a2fadf9cb70f566a.js %}
Next, let’s look at the methods that the Product POJO utilizes for data management.

## The constructor method

The public constructor does a couple of things:

* Overrides the PLACEHOLDER_PRODUCTS_TABLE_NAME table name annotation value with the actual value from the environment variable

* Gets an instance of DynamoDBAdapter

* Gets an instance of AmazonDynamoDB client

* Gets an instance of DynamoDBMapper
{% gist https://gist.github.com/richardgrantserverless/f984ab94031bfa7abf62d9d32b53af19.js %}
## The list() method

The list() method uses a DynamoDBScanExpression construct to retrieve all the products from the products table. It returns a list of products via the List<Product> data structure. It also logs the list of products retrieved.
{% gist https://gist.github.com/richardgrantserverless/425fae9891bfa8325f51d7ad7bcb4d29.js %}
## The get() method

The get() method takes a product id and uses a DynamoDBQueryExpression to set up a query expression to match the passed in product id. The mapper object has a query method that is passed the queryExp, to retrieve the matching product:
{% gist https://gist.github.com/richardgrantserverless/b9be15dbb3a202b0ea10a19312aed994.js %}
## The save() method

The save() method takes a product instance populated with values, and passes it to the mapper object's save method, to save the product to the underlying table:
{% gist https://gist.github.com/richardgrantserverless/534071054bb3ded4f73b114c01ed05e3.js %}
## The delete() method

The delete() method takes a product id and then calls the get() method to first validate if a product with a matching id exists. If it exists, it calls the mapper object's delete method, to delete the product from the underlying table:
{% gist https://gist.github.com/richardgrantserverless/b272a8f5cd5cf6dc56a45fdf2987b2f5.js %}
**Note**: The Product POJO class can be independently tested to make sure the data management functionality works against a DynamoDB table. This seperation allows us to write unit tests to test the core DAL functionality.

## Implementing the API

Now, that our Product DAL is written up and works as expected, we can start looking at the API function handlers that will be calling the Product DAL to provide the expected functionality.

We will define the API endpoints, then map the events to the handlers and finally write the handler code.

## The API Endpoints

Before we look at the API handlers, let’s take a look at the API endpoints that we will map to the handlers.

The API endpoints will look like:

POST /products: Create a product and save it to the DynamoDB table.

GET /products/: Retrieves all existing products.

GET /products/{id}: Retrieves an existing product by id.

DELETE /products/{id}: Deletes an existing product by id.

## Mapping Events to Handlers

To implement the API endpoints we described above, we need to add events that map our API endpoints to the corresponsing Lambda function handlers.

Update the following sections in the serverless.yml:
{% gist https://gist.github.com/richardgrantserverless/8ad94b0f7c7cf3ede34ccb36c18c8e35.js %}
## Writing the Handlers

Let’s write the code for the four handlers that will provide us the needed functionality to implement the Products REST API. Let’s copy the Handler.java file that was generated by the boilerplate and create four new files under the src/main/java/com/serverless folder. We can now delete the Handler.java file.

* CreateProductHandler.java

* ListProductHandler.java

* GetProductHandler.java

* DeleteProductHandler.java

The basic code for all the handlers are the same. Each handler is defined as a class that implements RequestHandler from the AWS Lambda runtime. Then the handleRequest method is overriden in the class to provide the custom logic for the handler. The handleRequest method receives a Map object with the inputs from the caller and a Context object with information about the caller's environment.

## Create Product Handler

If the call is successful, a 200 OK response is returned back. In case of an error or exception, the exception is caught and a 500 Internal Server Error response is returned back:
{% gist https://gist.github.com/richardgrantserverless/65cd5799b1b02d14f1cd56d4b99049a4.js %}
## List Product Handler

The ListProductHandler calls the list() method on the product instance to get back a list of products.

If the call is successful, a 200 OK response is returned back. In case of an error or exception, the exception is caught and a 500 Internal Server Error response is returned back:
{% gist https://gist.github.com/richardgrantserverless/f3f0bc3d406359a02e22d7fd8b77a4f0.js %}
## Get Product Handler

The GetProductHandler receives the id via the path parameters attribute of the input. Then it calls the get() method on the product instance passes it the id to get back a matching product.

If the call is successful, a 200 OK response is returned back. If no products with the matching id are found, a 404 Not Found response is returned back. In case of an error or exception, the exception is caught and a 500 Internal Server Error response is returned back:
{% gist https://gist.github.com/richardgrantserverless/884bc236a5ad8f8bb32793b1af547ae3.js %}
## Delete Product Handler

The DeleteProductHandler receives the id via the path parameters attribute of the input. Then it calls the delete() method on the product instance passing it the id to delete the product.

If the call is successful, a 204 No Content response is returned back. If no products with the matching id are found, a 404 Not Found response is returned back. In case of an error or exception, the exception is caught and a 500 Internal Server Error response is returned back:
{% gist https://gist.github.com/richardgrantserverless/7e56420bb8bb1dc2e3a74111bc1108ff.js %}
**Note:** The full [source code](https://github.com/rupakg/aws-java-products-api) for the project is available on Github.

## Deploying the service

Now that we’ve looked at the code and understand the overall workings of the service, let’s build the Java code, and deploy the service to the cloud.

To build the Java code:
{% gist https://gist.github.com/richardgrantserverless/2673237a814508fd63d3e0380af03129.js %}
After a successful build, we should have an artifact at aws-java-products-api/target/products-api-dev.jar that we will use in our deployment step.

Let’s deploy the service to the cloud:
{% gist https://gist.github.com/richardgrantserverless/75fcb3c02141fed8d24ccaaa9b22e73c.js %}
On a successful deployment, we will have our four API endpoints listed as shown above.

## Calling the API

Now that we have a fully functional REST API deployed to the cloud, let’s call the API endpoints.

### Create Product
{% gist https://gist.github.com/richardgrantserverless/d19d87cdfd8394ddc6b3c2f827766c45.js %}
Now, we’ll make a few calls to add some products.

## List Products

Here’s the java-products-dev DynamoDB table listing our products:
{% gist https://gist.github.com/richardgrantserverless/e2bbc3d60f7eefc4014acbdda9d05f13.js %}
![](https://cdn-images-1.medium.com/max/3716/0*23DVlIFcf3Pli79U.png)

**No Product(s) Found:**
{% gist https://gist.github.com/richardgrantserverless/0619009f2588a73f787122f09c1846fe.js %}
## Get Product
{% gist https://gist.github.com/richardgrantserverless/a3d3a652995abbeada509ebefa9e0e9c.js %}
**Product Not Found:**
{% gist https://gist.github.com/richardgrantserverless/54bb0b102c1b1d5fe316465e7cd28404.js %}
## Delete Product
{% gist https://gist.github.com/richardgrantserverless/19ae38510714f66a56257669c71af659.js %}
**Product Not Found:**
{% gist https://gist.github.com/richardgrantserverless/282456de258b9c0a30c8b6f5571e6395.js %}
## View the CloudWatch Logs

We have used the log4j.Logger in our Java code to log relevant info and errors to the logs. In case of AWS, the logs can be retrieved from CloudWatch.

Let’s do a GET call and then take a look at the logs from our terminal:
{% gist https://gist.github.com/richardgrantserverless/2f61dbfe3bd5687d1352e3fd63d11715.js %}{% gist https://gist.github.com/richardgrantserverless/795c986420cb3825dc44302a4db71309.js %}
Notice the lines about the database connection being open/closed, the request data structure going to DynamoDB and then the response coming back, and finally the response data structure that is being returned by our API code.

## Removing the service

At any point in time, if you want to remove the service from the cloud you can do the following:
{% gist https://gist.github.com/richardgrantserverless/f1894b6547979179e3a107a25a647c00.js %}
It will cleanup all the resources including IAM roles, the deployment bucket, the Lambda functions and will also delete the DynamoDB table.

## Summary

To recap, we used Java to create a serverless REST API service, built it and then deployed it to AWS. We took a deep dive into the DAL code that handles the backend data mapping and access to the DynamoDB table. We also looked at the mapping between events, the API endpoints and the lambda function handlers in the service, all described intuitively in the serverless.yml file.

By now, you should have an end-to-end implementation of a serverless REST API service written in Java and deployed to AWS.

Hope you liked the post, and feel free to give me your feedback or ask any questions, in the comments below.

*Originally published at [https://www.serverless.com](https://www.serverless.com/blog/how-to-create-a-rest-api-in-java-using-dynamodb-and-serverless).*