Calling Lambda Functions Through AWS API Gateway

Calling Lambda Functions Through AWS API Gateway

In recent times, most people are moving towards FaaS (Functions-as-a-Service). This article shows how to write a Lambda service in AWS and to call it through the AWS API gateway.

How to Write a Lambda Function Using Java

  • Create a Java Maven project.
  • Edit the Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>lk.sidath.cloud</groupId>
    <artifactId>cloud-lambda</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-core</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-events</artifactId>
            <version>2.2.5</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
  • Create a class named “APIRequestHandler.java.”
package lk.sidath.cloud;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class APIRequestHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent, Context context) {

        APIGatewayProxyResponseEvent apiGatewayProxyResponseEvent = new APIGatewayProxyResponseEvent();
        try {
            String requestString = apiGatewayProxyRequestEvent.getBody();
            JSONParser parser = new JSONParser();
            JSONObject requestJsonObject = (JSONObject) parser.parse(requestString);
            String requestMessage = null;
            String responseMessage = null;
            if (requestJsonObject != null) {
                if (requestJsonObject.get("requestMessage") != null) {
                    requestMessage = requestJsonObject.get("requestMessage").toString();
                }
            }
            Map<String, String> responseBody = new HashMap<String, String>();
            responseBody.put("responseMessage", requestMessage);
            responseMessage = new JSONObject(responseBody).toJSONString();
            generateResponse(apiGatewayProxyResponseEvent, responseMessage);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return apiGatewayProxyResponseEvent;
    }

    private void generateResponse(APIGatewayProxyResponseEvent apiGatewayProxyResponseEvent, String requestMessage) {
        apiGatewayProxyResponseEvent.setHeaders(Collections.singletonMap("timeStamp", String.valueOf(System.currentTimeMillis())));
        apiGatewayProxyResponseEvent.setStatusCode(200);
        apiGatewayProxyResponseEvent.setBody(requestMessage);
    }
}

How to Create a Lambda Function in AWS

Sign in to the AWS account and go to the Lambda service under “Services.”

According to the above image, we can start creating the function from scratch. There are several runtime environments and I chose Java 8 for this example.

We need to have permission for the lambda function. For that, I have created a new role with the basic lambda permission.

In order to create a lambda function, you need to upload the build jar.

  • Go to the project home and build the Maven project using  mvn clean install .
  • Upload the jar located inside the target folder.
  • Fill the handler info as with lk.sidath.cloud.APIRequestHandler::handleRequest.
  • Save the function.

Now the lambda function is ready to be invoked via the API Gateway. The best way to secure the lambda function is by calling those services via a gateway. So we use the AWS API gateway to secure the lambda function and it also gives API management.

How to Configure API Gateway

Drag and drop the API Gateway from the left panel. After that, you can configure the API Gateway.

In this configuration, we can define the API as a new API and can provide the security with the API key. After creating a new API you can see the API details with the API key.

Start the serverless function using the AWS API gateway.


The above image shows how testing is done and its integration. This is the default integration of the AWS environment.

The test client, which is provided by AWS, is very good and we can control all input parameters for our function. We can select the method, pass the query params, change the headers, change the request body and so on. They also provide the request and response logs and details related to the response such as HTTP status, response time, response body and headers.

We can call this function using the curl or postman from our local pc.

https://o6e.execute-api.us-west-5.amazonaws.com/default/FirstLambdaFunction \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \ -H 'x-api-key: *****************************' \ -d '{ "requestMessage": "Sidath"}'

from DZone Cloud Zone

Sharing is caring!

Comments are closed.