Create and Deploy AWS Lambda Java Application

AWS Lambda is a serverless service where we can deploy and run our application code or backend service without worrying about managing resources the code will require. AWS Lambda is auto-managed which takes care of all the compute resources, including maintenance of server and operating system, code monitoring and logging, capacity provisioning and auto scaling.

In this tutorial, we will:

  • Build a sample Java application for AWS Lambda.
  • Deploy the Java jar file to AWS Lambda.
  • Create Amazon API Gateway and point to the AWS Lambda function.
  • Test the Lambda function.

What You'll Need

Follow the steps below to complete this tutorial:

Create AWS Lambda Java Project

We assume that you have an AWS account and have an Eclipse IDE for Enterprise Java and Web Developers already installed on your computer.

The next thing we need to do, is installed the AWS Toolkit for Eclipse . To install this, go to Eclipse Marketplace from the Help menu of your Eclipse IDE, search for aws toolkit and when it is found, install it.

To create a Lambda project
  1. Open the new project creation wizard of Eclipse and then choose AWS Lambda Java Project.
  2. Add a Project Name, Group ID, Artifact ID, and Class Name in the associated input fields. This example uses the following values:
    • Project Name : MyLambda
    • Group ID : com.example.lambda
    • Artifact ID : demo
    • Class Name : MainHandler

    The default value of the Package Name field is the concatenation of the Group ID and Artificat ID. This value is automatically updated when the value of Group ID and Artifact ID are updated. The package name is the package namespace for the AWS Lambda handler class.

  3. For Input Type, choose Custom. For information about these input types, see below:
    • S3 Event - It receives an event from Amazon S3 event.
    • SNS Event - It receives an event from Amazon SNS.
    • Kinesis Event - It receives an event from an Amazon Kinesis stream.
    • Cognito Event - It receives and event from Amazon Cognito.
    • Custom - It receives an event from custom code. We can give a custom name to the custom input type. By default, the generic Object type is used.
  4. Verify everything as shown in the image below and then choose Finish.
  5. After choosing Finish, your project's directory and source files are generated in your Eclipse workspace.
Add New POJO classes

In your code package, create two new POJO classes Request.java and Response.java.


package com.example.lambda.demo;

public class Request {

    private String httpMethod;
    private int id;

    public String getHttpMethod() {
        return httpMethod;
    }

    public void setHttpMethod(String httpMethod) {
        this.httpMethod = httpMethod;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

}

package com.example.lambda.demo;

public class Response {

    private int messageId;
    private String message;
    private String status;

    public int getMessageId() {
        return messageId;
    }

    public void setMessageId(int messageId) {
        this.messageId = messageId;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

}
Implement handleRequest Method

Open up MainHandler.java class and implement the handleRequest method. This method is the entry point for your Lambda function, and it will be invoked by Lambda in response to input from the event sources of your function.

Update the code of the MainHandler.java class as shown in the example below:


package com.example.lambda.demo;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class MainHandler implements RequestHandler {

    @Override
    public Response handleRequest(Request input, Context context) {
        context.getLogger().log("Input: " + input);

        Response response = new Response();

        switch (input.getHttpMethod()) {
            case "GET": {
                response.setMessageId(input.getId());
                response.setMessage("Hello from GET method!");
                response.setStatus("Success");
                return response;
            }
            case "POST": {
                response.setMessageId(input.getId());
                response.setMessage("Hello from GET me");
                response.setMessage("Hello from POST method!");
                response.setStatus("Success");
                return response;
            }
            default: {
                break;
            }
        }

        response.setStatus("Failed");
        return response;
    }

}

Now, go to your code test package, and update the code in the MainHandlerTest.java class as shown in the example below, so that there is no test failures while building the project jar file:


package com.example.lambda.demo;

import java.io.IOException;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.amazonaws.services.lambda.runtime.Context;

/**
 * A simple test harness for locally invoking your Lambda function handler.
 */
public class MainHandlerTest {

    private static Request input;

    @BeforeClass
    public static void createInput() throws IOException {
        // TODO: set up your sample input object here.
        input = new Request();
        input.setHttpMethod("GET");
        input.setId(1);
    }

    private Context createContext() {
        TestContext ctx = new TestContext();

        // TODO: customize your context here if needed.
        ctx.setFunctionName("Your Function Name");

        return ctx;
    }

    @Test
    public void testMainHandler() {
        MainHandler handler = new MainHandler();
        Context ctx = createContext();

        Response output = handler.handleRequest(input, ctx);

        // TODO: validate output here if needed.
        Assert.assertEquals("Success", output.getStatus());
    }
}
Build the Project Jar File

To build the project jar file, right click on the project and from the toolbar, choose to Run As, Maven Build.

Create and Deploy a Lambda Function (AWS Console)
  1. Login to the AWS Management Console and open the AWS Lambda console at https://console.aws.amazon.com/lambda .
  2. Choose Create function.
  3. On the Create function page, choose Author from scratch.
  4. On the Basic information page, do the following:
    • Type your Lambda function name - myFunctionForTestAPI.
    • Choose Runtime - Java 11.
    • For the Execution Role, choose Create a new role with basic Lambda permissions .
    • Leave the other default values.
  5. Choose Create function.
  6. On the Edit Runtime settings page, update Handler with your project's package.name.Handlerclass::functionName .
  7. From the Upload From browsing option, choose and upload your project jar file that you have built. In our case, it is located in MyLambda/target/demo-1.0.0.jar .
Create Amazon API Gateway
  1. Open the Amazon API Gateway console at https://console.aws.amazon.com/apigateway .
  2. Choose Rest API.
  3. On the Create new API page, do the following:
    • Choose New API.
    • Type your API name. For this example, We will use MyTestAPI.
    • In the Description field, write something about your API.
    • For Endpoint Type, choose Regional.
  4. Choose Create API.
  5. From the Actions dropdown list, choose Create Resource.
  6. On the New Child Resource page, do the following:
    • Type Resource Name. For our example, we will use message.
    • Type Resource Path. For our example, we will use message.
    • Choose Create Resource.
  7. From the Actions dropdown list, choose Create Resource again to create a new Resource for getting id from the API.
  8. On the New Child Resource page, do the following:

    • Type id in Resource Name field.
    • Type {id} in Resource Path field.
    • Choose Create Resource.
  9. Now, create Method for the Resource we created. From the Actions dropdown list, choose Create Method.
  10. From the dropdown list of methods, choose GET and save.
  11. On the Method Set up page, type your Lambda function name in Lambda Function field. Our Lambda function name for this example is myFunctionForTestAPI.
  12. Choose Save.
  13. Next, we will see Execution Method page as shown in the example below:
  14. On the Execution Method page, click on Integration Request.
  15. Under the Mapping Templates, do the following:
    • For Request body passthrough, choose When there are no templates defined(recommended).
    • Click on Add mapping template.
    • Type application/json in Content-Type field.
    • From the Generate Template dropdown list, select empty.
    • In the Generate Template body set the code as follows:
    • 
      #set($inputRoot = $input.path('$'))
      {
        "httpMethod":"$context.httpMethod",
        "id":$input.params("id")
      }
      
    • Choose Save and the GET API is ready.
  16. From the Actions dropdown list, choose Deploy API.
  17. On the Deploy API options, do the following:
    • Choose [New State]
    • For Stage name, type dev
    • For Stage and Deployment description, type some information that is relevant to your deployment.
    • Choose Deploy.
  18. After deploying the API, you will be redirected to the Stage Editor page where you will find the Invoke URL as shown in the image below. Use this URL to call the Lambda functions.
Test the Lambda Function

Invoke the GET method /message/{1} using an HTTP requester such as POSTMAN. Example shown in the image below:

Summary

Congratulations! you have learned how to create, deploy and invoke a Lambda function using Java and Amazon API Gateway.