If you have a few years of experience in the Java ecosystem, and you're interested in sharing that experience with the community (and getting paid for your work of course), have a look at the "Write for Us" page. Cheers. Eugen

The new Certification Class of REST With Spring is out:

>> CHECK OUT THE COURSE

1. Introduction

AWS Lambda is serverless computing service provided by Amazon Web Services and WS DynamoDB is a NoSQL database service also provided by Amazon.

Interestingly, DynamoDB supports both document store and key-value store and is fully managed by AWS.

Before we start, note that this tutorial requires a valid AWS account (you can create one here). Also, it’s a good idea to first read the AWS Lambda with Java article.

2. Maven Dependencies

To enable lambda we need the following dependency which can be found on Maven Central:

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-lambda-java-core</artifactId>
    <version>1.1.0</version>
</dependency>

To use different AWS resources we need the following dependency which also can also be found on Maven Central:

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-lambda-java-events</artifactId>
    <version>1.3.0</version>
</dependency>

And to build the application, we’re going to use the Maven Shade Plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.0.0</version>
    <configuration>
        <createDependencyReducedPom>false</createDependencyReducedPom>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
        </execution>
    </executions>
</plugin>

3. Lambda Code

There are different ways of creating handlers in a lambda application:

  • MethodHandler
  • RequestHandler
  • RequestStreamHandler

We will use RequestHandler interface in our application. We’ll accept the PersonRequest in JSON format, and the response will be PersonResponse also in JSON format:

public class PersonRequest {
    private String firstName;
    private String lastName;
    
    // standard getters and setters
}
public class PersonResponse {
    private String message;
    
    // standard getters and setters
}

Next is our entry point class which will implement RequestHandler interface as:

public class SavePersonHandler 
  implements RequestHandler<PersonRequest, PersonResponse> {
    
    private DynamoDB dynamoDb;
    private String DYNAMODB_TABLE_NAME = "Person";
    private Regions REGION = Regions.US_WEST_2;

    public PersonResponse handleRequest(
      PersonRequest personRequest, Context context) {
 
        this.initDynamoDbClient();

        persistData(personRequest);

        PersonResponse personResponse = new PersonResponse();
        personResponse.setMessage("Saved Successfully!!!");
        return personResponse;
    }

    private PutItemOutcome persistData(PersonRequest personRequest) 
      throws ConditionalCheckFailedException {
        return this.dynamoDb.getTable(DYNAMODB_TABLE_NAME)
          .putItem(
            new PutItemSpec().withItem(new Item()
              .withString("firstName", personRequest.getFirstName())
              .withString("lastName", personRequest.getLastName());
    }

    private void initDynamoDbClient() {
        AmazonDynamoDBClient client = new AmazonDynamoDBClient();
        client.setRegion(Region.getRegion(REGION));
        this.dynamoDb = new DynamoDB(client);
    }
}

Here when we implement the RequestHandler interface, we need to implement handleRequest() for the actual processing of the request. As for the rest of the code, we have:

  • PersonRequest object – which will contain the request values passed in JSON format
  • Context object –  used to get information from lambda execution environment
  • PersonResponse – which is the response object for the lambda request

When creating a DynamoDB object, we’ll first create the AmazonDynamoDBClient object and use that to create a DynamoDB object. Note that the region is mandatory.

To add items in DynamoDB table, we’ll make use of a PutItemSpec object – by specifying the number of columns and their values.

We don’t need any predefined schema in DynamoDB table, we just need to define the Primary Key column name, which is “id” in our case.

4. Building the Deployment File

To build the lambda application, we need to execute the following Maven command:

mvn clean package shade:shade

Lambda application will be compiled and packaged into a jar file under the target folder.

5. Creating the DynamoDB Table

Follow these steps to create the DynamoDB table:

  • Login to AWS Account
  • Click “DynamoDB” that can be located under “All Services”
  • This page will show already created DynamoDB tables (if any)
  • Click “Create Table” button
  • Provide “Table name” and “Primary Key” with its datatype as “Number”
  • Click on “Create” button
  • Table will be created

6. Creating the Lambda Function

Follow these steps to create the Lambda function:

  • Login to AWS Account
  • Click “Lambda” that can be located under “All Services”
  • This page will show already created Lambda Function (if any) or no lambda functions are created click on “Get Started Now”
  • “Select blueprint” -> Select “Blank Function”
  • “Configure triggers” -> Click “Next” button
  • “Configure function”
    • “Name”: SavePerson
    • “Description”: Save Person to DDB
    • “Runtime”: Select “Java 8”
    • “Upload”: Click “Upload” button and select the jar file of lambda application
  • “Handler”: com.baeldung.lambda.dynamodb.SavePersonHandler
  • “Role”: Select “Create a custom role”
  • A new window will pop and will allow configuring IAM role for lambda execution and we need to add the DynamoDB grants in it. Once done, click “Allow” button
  • Click “Next” button
  • “Review”: Review the configuration
  • Click “Create function” button

7. Testing the Lambda Function

Next step is to test the lambda function:

  • Click the “Test” button
  • The “Input test event” window will be shown. Here, we’ll provide the JSON input for our request:
{
  "id": 1,
  "firstName": "John",
  "lastName": "Doe",
  "age": 30,
  "address": "United States"
}
  • Click “Save and test” or “Save” button
  • The output can be seen on “Execution result” section:
{
  "message": "Saved Successfully!!!"
}
  • We also need to check in DynamoDB that the record is persisted:
    • Go to “DynamoDB” Management Console
    • Select the table “Person”
    • Select the “Items” tab
    • Here you can see the person’s details which were being passed in request to lambda application
  • So the request is successfully processed by our lambda application

8. Conclusion

In this quick article, we have learned how to create Lambda application with DynamoDB and Java 8. The detailed instructions should give you a head start in setting everything up.

And, as always, the full source code for the example app can be found over on Github.

Go deeper into building a REST API with Spring:

>> CHECK OUT THE COURSE