AWS API Gateway请求主体为Java POJO以实现功能 [英] AWS API Gateway request body as Java POJO for function
问题描述
使用aws-lambda,API Gateway和无服务器框架只是一个真正的基本问题.我只想将发布请求的主体作为Java POJO移交.
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.
好的,这是设置:
POJO:
public class Person {
private String lastName;
private string firstName;
... Setters and Getters omitted
}
处理程序:
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"
}
最后但并非最不重要的serverless.yml
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?
不幸的是,这不是那么简单.调用函数时,Person POJO始终为空.我们如何在AWS API Gateway& Lambda?
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?
推荐答案
好吧,经过长时间的研究和一些猜测,我找到了答案,并决定将其发布在这里,以供将来我(和其他人)使用.
Well, through prolonged research and some guessing I found the answer and decided to post it here for future me (and others) to find.
但是首先,让我们看一下实际问题.身体不会在根中,而是在input.body下,然后杰克逊不知道在哪里可以找到你的人.
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.
因此,首先我们需要从lambda-proxy-integration更改为lambda-integration.
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.
这为我们提供了以下serverless.yml:
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,现在您的POJO将被填充. 希望这会有所帮助,并让我知道是否有人找到了一个更简单或更佳的解决方案.
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.
来源:
https://serverless.com/framework/docs/providers/aws/events/apigateway/#request-templates
无法解析请求正文转换成json:意外字符(\'-\'(代码45))AWS Lambda + API + Postman (用于格式化yml)
Could not parse request body into json: Unexpected character (\'-\' (code 45)) AWS Lambda + API + Postman (for formatting the yml)
这篇关于AWS API Gateway请求主体为Java POJO以实现功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!