How to Invoke and Test an AWS Lambda Function Locally with Java

What is AWS Lambda?

AWS Lambda is an Amazon’s service for hosting code without the need to maintain a server to host it on. You simply write your function, upload it to Amazon and use it – let them worry about finding actual resources to run it on.

Invoke and Test AWS Lambda Functions Locally with Java

In this example, we’re going to work with an AWS Lambda function called “GetWeatherDataFunction”. This function takes a city name and country as a request in JSON format.

The response of the Lambda function is the weather condition for the given city. The output is also in JSON format.

First, we create an InvokeRequest which will call our Lambda Function with a payload, the JSON request.

We also need to be authenticated against AWS, so we need to pass in our accessKey and secretKey in the BasicAWSCredentials.

We then invoke the Lambda Function with the details

Note: The provided accessKey and secretKey in the below example are made up. You will need to provide your own credentials.

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.AWSLambdaClientBuilder;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.InvokeResult;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.nio.ByteBuffer;

public class LambdaInvoke {

    public static void main(String[] args) {

        InvokeRequest invokeRequest = new InvokeRequest()
                .withFunctionName("GetWeatherDataFunction")
                .withPayload("{\n" +
                        " \"city\": \"Paris\",\n" +
                        " \"countryCode\": \"FR\"\n" +
                        "}");

        BasicAWSCredentials awsCreds = new BasicAWSCredentials("APIADGALD", "PQFNsMOxyrb");

        AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                .withRegion(Regions.US_EAST_1)
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();

        InvokeResult invokeResult = null;

        try {
            invokeResult = awsLambda.invoke(invokeRequest);
        }
        catch (Exception e) {
            System.out.println(e);
        }

        System.out.println(invokeResult.getStatusCode());
    }
}

If everything works as expected, we should get a 200 status code being printed on the console.

How to Parse the Results of the AWS Lambda Function

The output of the above call is of type ByteBuffer which we will need to convert to String to parse the JSON response.

We can also use the ObjectMapper class from the Jackson Library to map our JSON response to our POJOs.

ByteBuffer byteBuffer = invokeResult.getPayload();

        String rawJson = null;

        try {
        rawJson = new String(byteBuffer.array(), "UTF-8");
        }catch (Exception e) {

        }

        System.out.println(rawJson);

        ObjectMapper mapper = new ObjectMapper();

        try {
        Response response = mapper.readValue(rawJson, Response.class);
        System.out.println(response.getWeather().get(0).getMain() + "\t" + response.getWeather().get(0).getDescription());

        } catch(Exception e) {

        }

The output is something similar to

200
{"weather":[{"main":"Clouds","description":"broken clouds"}]}
Clouds broken clouds

Here is the complete code

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.AWSLambdaClientBuilder;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.InvokeResult;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.nio.ByteBuffer;

/**
 * Created by itahg on 03/05/2017.
 */
public class LambdaInvoke {

    public static void main(String[] args) {

        InvokeRequest invokeRequest = new InvokeRequest()
                .withFunctionName("GetWeatherDataFunction")
                .withPayload("{\n" +
                        " \"city\": \"Paris\",\n" +
                        " \"countryCode\": \"FR\"\n" +
                        "}");

        BasicAWSCredentials awsCreds = new BasicAWSCredentials("APIADGALD", "PQFNsMOxyrb");

        AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                .withRegion(Regions.US_EAST_1)
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();

        InvokeResult invokeResult = null;

        try {
            invokeResult = awsLambda.invoke(invokeRequest);
        }
        catch (Exception e) {

        }

        System.out.println(invokeResult.getStatusCode());

        ByteBuffer byteBuffer = invokeResult.getPayload();

        String rawJson = null;

        try {
            rawJson = new String(byteBuffer.array(), "UTF-8");
        }catch (Exception e) {

        }

        System.out.println(rawJson);

        ObjectMapper mapper = new ObjectMapper();

        try {
            Response response = mapper.readValue(rawJson, Response.class);
            System.out.println(response.getWeather().get(0).getMain() + "\t" + response.getWeather().get(0).getDescription());

        } catch(Exception e) {

        }

    }
}

Leave a Reply