AWS Lambda function with Java Pojo as Input Output Example

In the previous tutorial, we saw How to Create AWS Lambda function with Java and we passed String as input and also returned String as Output.I will recommend to go through that tutorial first, if you are creating lambda function for the first time.

In this tutorial, we will see, how we can pass Java Plain old Java object(POJO) as input and also return it as Output.



Here we will be implementing RequestHandler interface.
package com.blogspot.javasolutionsguide;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.blogspot.javasolutionsguide.input.Input;
import com.blogspot.javasolutionsguide.output.Output;

public class HelloWorldWithPojoInputOutput implements RequestHandler<Input, Output> {

    @Override
    public Output handleRequest(Input input, Context context) {
        String message = String.format("Hello %s%s.", input.getName(), " " + "from" + context.getFunctionName());
        return new Output(message);
    }
}

And here is our Input and Output classes.
package com.blogspot.javasolutionsguide.input;

public class Input {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

package com.blogspot.javasolutionsguide.output;

public class Output {
    private String message;

    public Output(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

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

For uploading the code to AWS console, please follow steps from my previous tutorial.

Once you have uploaded your jar in AWS lambda console, click on "Select a Test event" and then "configure test events".

Enter event name as "HelloWorldWithPojoInputOutput" and replace following:
{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

with following :
{
  "name" : "Gaurav Bhardwaj"
}

Click on Create button. Now click on Test button and you should see your lambda fucntion executed successfully with message "Hello Gaurav Bhardwaj", which is the output returned by our lambda function.

You can find all code of this tutorial in GitHub

Summary

So in this tutorial, we saw how we can pass POJO to lambda function and also we can return POJO from a lambda function.