Integrate Spring Boot With Amazon DynamoDB

Published by Vignesh M on

In this post, let’s see how to integrate Spring Boot with Amazon DynamoDB. I have been exploring the option of creating the REST API using Spring Boot backed by DynamoDB. I will share the information that I have learned during the development process with a simple project named Tasklet API.

Let’s build our project on top of the example we have used in the spring boot starter post. The complete project we are going to develop in this post can be downloaded from here or from the downloads section available at the end of this post.

Prerequisite tools

    1. Java 1.8 or higher
    2. Eclipse IDE
    3. Maven

DynamoDB library for Java

To make the integration between Spring based applications and DynamoDB easier, we can make use of the community module Spring Data DynamoDB. I assume that you have imported the project used in the spring boot starter post.

Add the below dependency for spring-data-dynamodb in pom.xml

Using the Tasklet API, users should be able to add, read, edit and delete the Tasks.  As next step we need to create the data model class which represent the Task itself.

We have to represent the sub tasks as well for which another Model class SubTask to be defined.

DynamoDB Config

To access the DynamoDB from Spring Boot application, we need to create and register Spring beans for DynamoDB client.

To complete the configuration, add the entries for AWS access key and secret key in the application.properties.

Note:  When deploying the application into Amazon EC2 instance or Amazon ECS, we can make use of the IAM roles to access the other AWS services like DynamoDB or S3, instead of storing credentials in properties file. At this point of time, to develop this project let’s make use of credentials.

IAM Policy for accessing DynamoDB

For this project, I have created a IAM user named TaskletAPI and attached the below custom IAM policy. I have restricted the IAM policy to have access only for DynamoDB operations on a specific table named Tasks.

Repository interface for CRUD operations

Since we have spring-data-dynamodb in our classpath, we can make use of CRUD repository for our database operations. With @EnableScan annotation, the repository implementation will be registered as a component in the Spring container.

REST controller

Okay. Now we are all set to write our controller class for handling the incoming requests. Let’s write handler methods for writing/fetching user task to/from DynamoDB. Our controller class looks as shown in below listing.

@PostMapping annotation indicates that the HTTP POST request with URI http://<domain>:<port>/tasklet/task will be handled and the data will be saved to database. The call is then delegated to service class from the controller.

Similarly, @GetMapping annotation on method getTaskByUserId indicates that HTTP GET request with URI http://<domain>:<port>/tasklet/task/{userid}will be handled and the data will be returned after fetching from database.

HttpResponse and TaskMetaData are helper classes to form the ResponseEntity.

HttpResponse.java

TaskMetaData.java

Managing API versions

If we need to manage the API versions going further, we can do that using Query params in the request URI. For example, if we have this application running on port 8080, then issue the request as below:

with query param

http://localhost:8080/tasklet/task?version=2

In this case, we can route to the appropriate service method for processing the request.

without query param

http://localhost:8080/tasklet/task

If we define the query param as optional, then by default we can route to the latest api version service method if the version param is not present in request.

Unit testing

We have completed developing our Tasklet service. Let’s write some unit tests to ensure that the application is working as expected.

Testing with Postman API client

Before testing with Postman client, make sure the application is up and running. It should run on the default port 8080 since we haven’t explicitly configured the server’s port.

Launch the Postman client and make a HTTP POST request to http://localhost:8080/tasklet/task?version=1 .  Input the below sample request.

You should see the response similar to the one shown in the below listing.

Conclusion

We have seen how to integrate Spring Boot with Amazon DynamoDB . Finally, we have written unit tests to test our Tasklet API service. We will add more features of Spring Boot and Spring Cloud to our application in the upcoming posts. Stay tuned!

The source code we have worked on so far is available in the downloads section. If you have any questions, feel free to post it in the comments section. Thank you.


Download source code : spring-boot-with-dynamodb.zip



Vignesh M

Java developer , AWS Certified Solutions Architect Associate and Cloud technology enthusiast. Currently working for Hexaware technologies. He believes that knowledge increases by sharing not by saving.

4 Comments

Nisar · October 9, 2018 at 6:46 am

Vignesh – The article is awesome.

Just a quick question.
I want to know if it makes sense to just go with aws sdk (“aws-java-sdk-dynamodb” – see the url below) as opposed to “spring-data-dynamodb”:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Java.html

I know I’ll miss all the spring related eco-system capabilities if I chose “spring-data-dynamodb”. However, just using the aws sdk could be a reasonable option in my spring boot application?

    Vignesh M · October 12, 2018 at 6:14 am

    Nisar,
    The main advantage that spring-data-dynamodb brings is simplifying the data access layer with DynamoDB. If we use the aws-java-sdk-dynamodb, we have to deal with certain activities ourselves..like we will create UpdateItemSpec,GetItemSpec to perform operations on dynamoDB table.
    In short, if we need fine-grained control on the table operations, we have to go with aws-java-sdk-dynamodb library, otherwise spring-data-dynamodb should serve our purpose.

Rajib · October 9, 2018 at 9:05 am

I have used this code as same to same and changed access key and secret access key.but i am getting below error in postman.

“timestamp”: “2018-10-09T08:59:36.116+0000”,
“status”: 500,
“error”: “Internal Server Error”,
“message”: “The security token included in the request is invalid. (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: UnrecognizedClientException; Request ID: OOM30F157ERCRU4J4FHTQ2QUH7VV4KQNSO5AEMVJF66Q9ASUAAJG)”,
“path”: “/tasklet/task”

    Vignesh M · October 12, 2018 at 6:47 am

    Rajib,
    I have tested the code again, with valid credentials replaced. And it’s works.
    However, I was able to replicate your issue by making my credentials Inactive in the IAM console.
    Can you check whether that is the case for you? if your credentials are Inactive, you would get this error.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.