AWS API Gateway request body as Java POJO for function

本小妞迷上赌 提交于 2020-07-09 14:53:37

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/56687900/aws-api-gateway-request-body-as-java-pojo-for-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!