Hi readers, this is my second blog on AWS lambda, I covered the basics in my previous blogs. Now we will focus on the implementation part. Before starting, please keep a check on these things:
Prerequisite
- Setup your AWS account, click here
- Understanding what AWS Lambda is? click here
All set let’s start.
1) Configure lambda function on our AWS console.
Log in to the AWS account and go to AWS lambda console. You will get a basic lambda created with the hello world example. But we will create a new one so click on the create lambda function and fill in the necessary details and click on create function.
Now, you will get a page to configure the lambda. The first tab to set up the triggers for the function.
We get many triggers that can be set for a lambda function like setting an API gateway or an event triggered when we push something to the S3 bucket. Following are the triggers available:
- Amazon S3
- Amazon DynamoDB
- Amazon Kinesis Data Streams
- Amazon Simple Notification Service
- Amazon Simple Email Service
- Amazon Cognito
- AWS CloudFormation
- Amazon CloudWatch Logs
- Amazon CloudWatch Events
- AWS CodeCommit
- Scheduled Events (powered by Amazon CloudWatch Events)
- AWS Config
- Amazon Alexa
- Amazon Lex
- Amazon API Gateway
- AWS IoT Button
- Amazon CloudFront
- Amazon Kinesis Data Firehose
- Other Event Sources: Invoking a Lambda Function On Demand
- Sample Events Published by Event Sources
You can explore each one of them by click on it. In our example, we will use API gateway to interact with our lambda. So in order to create a new trigger click the API gateway option under add triggers.
2) Create a project
Now let’s create a java code that we want to run on our lambda. You can get the below code from my repository
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.handler; | |
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 com.example.models.Request; | |
import com.example.utils.constant.Constants; | |
import com.example.utils.fileprocessor.FileReader; | |
import com.example.models.Response; | |
import com.example.utils.config.ConfigReader; | |
import com.google.gson.Gson; | |
import java.nio.file.Paths; | |
public class LambdaHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { | |
private final ConfigReader configReader = ConfigReader.getConfigReader(Constants.LAMBDA); | |
private final Gson gson = new Gson(); | |
//Lambda Function | |
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent requestEvent, Context context) { | |
APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent(); | |
try { | |
//fetching the value send in the request body | |
String message = requestEvent.getBody(); | |
Request request = gson.fromJson(message, Request.class); | |
//fetching the response data from the json file | |
String responseFilePath = Paths.get(this.getClass() | |
.getResource("/") | |
.toURI()) | |
.toString() | |
+ configReader.getProperty(Constants.RESPONSE); | |
String responseData = FileReader.getDataFromFile(responseFilePath); | |
Response response = gson.fromJson(responseData, Response.class); | |
response.setMessage("Got " + request.getMessage() + "!!"); | |
//setting up the response message | |
responseEvent.setBody(gson .toJson(response)); | |
responseEvent.setStatusCode(200); | |
return responseEvent; | |
} catch(Exception ex) { | |
responseEvent.setBody(Constants.INVALID_RESPONSE); | |
responseEvent.setStatusCode(500); | |
return responseEvent; | |
} | |
} | |
} |
Let me highlight the main part of this code i.e the handleRequest function, which will handle the request coming in. It contains two parameters requestEvent and the context. requestEvent will bring in the request data which we will pass when we hit our lambda with the API gateway as a JSON body. The context object allows you to access useful information available within the Lambda execution environment like the memory limit, request id etc.
We are responding back with the APIGatewayProxyResponseEvent object where we set the body part and the status code.
3) Create a jar of the project and upload to the lambda
mvn clean package
Then upload the jar or zip file in the function code tab on the AWS lambda console and also we need to set the handler for the class on the consolepackage
.class
::method-reference
format.
4) Hit the API Gateway
Now we are ready with all the configurations and now let’s hit our lambda with the postman. Keep the request JSON body as:
{
“message” : “Hello Coders”
}
Wow, we got the response.
{
“status”: “Success”,
“message”: “Got Hello Coders!!”
}
Yeah, we have successfully completed our demo.
Try it yourself.
Thanks for your valuable time.
Reference: