Serverless Framework / Notes on implementation in AWS / Java.
API Gateway and Lambda do not work with the code generated by the template as it is, and it does not work! !!
For example, create a project with the following command.
sls create --template aws-java-maven --path serverless
Then the following Java file is created.
Handler.java
package hello;
import java.io.IOException;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class Handler implements RequestHandler<Request, Response> {
@Override
public Response handleRequest(Request input, Context context) {
return new Response("Go Serverless v1.0! Your function executed successfully!", input);
}
}
But if this method is executed through API Gateway, it won't work. Because the following JSON is passed (partially modified).
{
"httpMethod" : "POST",
"requestContext" : {
"httpMethod" : "POST",
"accountId" : "*******",
"apiId" : "*******",
"resourceId" : "******",
"identity" : {
"userAgent" : "Apache-HttpClient\/4.5.x (Java\/1.8.0_112)",
"userArn" : "arn:aws:iam::******:user\/****",
"caller" : "***************",
"cognitoAuthenticationProvider" : null,
"cognitoIdentityId" : null,
"accessKey" : "******************",
"accountId" : "*****************",
"sourceIp" : "test-invoke-source-ip",
"apiKey" : "test-invoke-api-key",
"cognitoAuthenticationType" : null,
"cognitoIdentityPoolId" : null,
"user" : "*******************"
},
"requestId" : "test-invoke-request",
"stage" : "test-invoke-stage",
"resourcePath" : "\/hello"
},
"resource" : "\/hello",
"pathParameters" : null,
"isBase64Encoded" : false,
"headers" : null,
"path" : "\/hello",
"stageVariables" : null,
"queryStringParameters" : null,
"body" : "{\n \"key1\": \"hoge\",\n \"key2\": 120\n}"
}
What I really want is the last `body`
property part.
It means that you need to write a program that extracts this.
Not only the request but also the response does not work as it is.
It seems that the response object needs three properties: `statusCode```,
headers```, and ``
body```.
~~ I will provide a sample solution to deal with this area. aws-serverless-java-sample ~~
(Fixed June 24, 2018) The AWS SDK has a corresponding solution, so I'll rewrite it.
When AWS provides a library called aws-lambda-java-events and connects Lambda to various services Request and response types are defined.
The types of requests and responses passed when connecting to API Gateway are as follows.
Since the body is a String type, the effort of JSON encode / decode remains, but it should still be much easier to code.
Recommended Posts