Creating a Lambda function for proxy integration

We will use a simple Lambda function, following the Lambda proxy integration example provided by AWS. We will only discuss the important code snippets that are used inside of the Lambda function within this chapter. However, you can refer to the code files for the complete code.

The Lambda Handler class implements the RequestStreamHandler interface, as follows:

public class ProxyStreamHandlerLambda implements RequestStreamHandler {

Along with the Context object, the handler method accepts the InputStream and OutputStream:

public final void handleRequest(final InputStream inputStream,
final OutputStream outputStream,
final Context context) throws IOException {

We can parse the InputStream to extract the event details sent by API Gateway as a JSONObject:

JSONParser parser = new JSONParser();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject event = (JSONObject) parser.parse(reader);

We are using the JSONParser from json-simple (com.googlecode.json-simple). The path, query, headers, and body can be extracted from the event, as follows:

JSONObject pathParams = (JSONObject) event.get("pathParameters");
String application = (String) pathParams.get("proxy");

JSONObject queryParams = (JSONObject) event.get("queryStringParameters");
String name = (String) queryParams.get("name");

JSONObject body = (JSONObject) parser.parse((String) event.get("body"));
String time = (String) body.get("time");

JSONObject headers = (JSONObject) event.get("headers");
String acceptHeader = (String) headers.get("Accept");
The complete working code, with the necessary checks (such as the null pointer check), is available in the code files.

For the response, we defined the response body and headers, and we added them (along with other parameters) to a JSONObject (responseJson):

JSONObject responseBody = new JSONObject();
responseBody.put("message", greeting);

JSONObject headers = new JSONObject();
headers.put("Content-Type", "application/json");

JSONObject responseJson = new JSONObject();
responseJson.put("isBase64Encoded", false);
responseJson.put("statusCode", "200");
responseJson.put("headers", headers);
responseJson.put("body", responseBody.toString());

Finally, let's add the response object to the OutputStream by using an OutputStreamWriter:

OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(responseJson.toJSONString());
writer.close();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.250.203