Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda function output as object

We are currently getting an AWS lambda response like this:

"{\"retailers\":[{\"address\":\"a\",\"retailerId\":1}, 
{\"address\":\"b\",\"retailerId\":2}]
,\"status\":{\"code\":200,\"type\":\"OK\",\"message\":\"Success\"}}" 

The response is converting to json at the API Gateway using a code snippet:

$util.escapeJavaScript("$input.path('$')").replaceAll("\\","")

How we can directly make a json output from lambda function and serve as response body with out using the escapeJavaScript function?

    public class GetRetailerInfo implements RequestHandler<Object, String> {

    @Override
    public String handleRequest(Object input, Context context) { 
        try{             
            JSONObject parameters=new JSONObject(input.toString());
            return APIUtil.getretailer(parameters,context).toString();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return "Unable to process the request. "+input;
    }
}
like image 687
Suresh AK Avatar asked Jun 29 '26 01:06

Suresh AK


1 Answers

By providing POJOs as generic input and output parameters to you RequestHandler implementation, AWS Lambda will take care of the serialization and deserialization between JSON and Java for you. The example below is copied from the Example 1: Creating Handler with Custom POJO Input/Output (Leverage the RequestHandler Interface) in the AWS Lambda developer guide:

package example;

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

public class Hello implements RequestHandler<Request, Response> {

    public Response handleRequest(Request request, Context context) {
        String greetingString = String.format("Hello %s %s.", request.firstName, request.lastName);
        return new Response(greetingString);
    }
}

For example, if the event data in the Request object is:

{
  "firstName":"value1",
  "lastName" : "value2"
}

The method returns a Response object as follows:

{
  "greetings": "Hello value1 value2."
}

Please follow the link above to see full example including implementations of the Request and Response classes.

like image 167
matsev Avatar answered Jun 30 '26 14:06

matsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!