Implement AWS Lambda Web Services with Java.
1. To create an execution role - Open the roles page in the IAM console. - Choose Create role. - Create a role with the following properties. - Trusted entity – Lambda. - Permissions – AWSLambdaBasicExecutionRole. - Role name – lambda-role. - The AWSLambdaBasicExecutionRole policy has the permissions that the function needs to write logs to CloudWatch Logs. - You can add permissions to the role later, or swap it out for a different role that's specific to a single function.
2. To create a Java function - Open the Lambda console. - Choose Create function. - Configure the following settings: - Name – my-function. - Runtime – Java 11. - Role – Choose an existing role. - Existing role – lambda-role. - Choose Create function. - To configure a test event, choose Test. - For Event name, enter test. - Choose Save changes. - To invoke the function, choose Test.
package cc.peerapat; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; import java.util.HashMap; import java.util.Map; /** * cc.peerapat.BahtTextHTTP::handleRequest */ public class BahtTextHTTP implements RequestHandler{ final Map headers = new HashMap<>(); public BahtTextHTTP() { headers.put("Content-Type", "text/plain"); } @Override public APIGatewayV2HTTPResponse handleRequest(final APIGatewayV2HTTPEvent request, final Context context) { return buildResponse(BahtText.toText(request.getBody())); } private APIGatewayV2HTTPResponse buildResponse(final String body) { final APIGatewayV2HTTPResponse response = new APIGatewayV2HTTPResponse(); response.setIsBase64Encoded(false); response.setStatusCode(200); response.setHeaders(headers); response.setBody(body); return response; } }