Reputation: 177
I was just having a really basic problem using aws-lambda, API Gateway and the serverless framework. I just wanted to hand over the body of a post request as a Java POJO.
Okay, so here's the setup:
POJO:
public class Person {
private String lastName;
private string firstName;
... Setters and Getters omitted
}
Handler:
public class PersonHandler implements RequestHandler<Person, ApiGatewayResponse> {
@Override
public ApiGatewayResponse handleRequest(lastNamePerson person, Context context) {
//... do something
}
}
And the payload in the post's request body would be
{
"lastName" : "John",
"firstName" : "Doe"
}
And, last but not least the serverless.yml
{
...
functions:person
handler:com.serverless.handler
event:
-http:
path:person
method:post
...
}
Well, looks pretty straight forward, doesn't it?
Unfortunately, it's not that simple. The Person POJO will always be empty when calling the function. How can we give the body as a POJO in AWS API Gateway & Lambda?
Upvotes: 1
Views: 2010
Reputation: 177
Well, through prolonged research and some guessing I found the answer and decided to post it here for future me (and others) to find.
But first, let's take a look at the actual problem. The body will not be in the root but under input.body, and then Jackson doesn't know where to find your person.
So, first we need to change from lambda-proxy-integration to lambda-integration.
And then we need to tell the integration to hand over the body as payload to the function.
This gives us the following serverless.yml:
{
...
functions:person
handler:com.serverless.handler
event:
-http:
path:person
method:post
integration:lambda
request:
template:
application/json:'$input.body'
...
}
e voila, now your POJO will be populated. Hope this helps, and let me know if anybody found a simpler or better solution to this.
Sources:
https://serverless.com/framework/docs/providers/aws/events/apigateway/#request-templates
Could not parse request body into json: Unexpected character (\'-\' (code 45)) AWS Lambda + API + Postman (for formatting the yml)
Upvotes: 3