刚刚通过 AWS 学习 - 我有一个 APIGateway REST API 设置与 Lambda 代理集成。 API 定义了一个模型,并使用该模型在主体上请求验证设置。
假设模型是
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"propertyA": {
"type": "string"
},
"propertyB": {
"type": "string"
},
"propertyC": {
"type": "string"
},
"propertyD": {
"type": "string"
}
},
"required": ["propertyA", "propertyB", "propertyC", "propertyD"]
}
现在,如果我通过 APIGateway 控制台测试 API,并故意提供无效输入(省略必需的属性 propertyD
):
{
"propertyA": "valueA",
"propertyB": "valueB",
"propertyC": "valueC"
}
请求失败并出现错误 (400):Sun Jul 11 13:07:07 UTC 2021:请求正文与内容类型 application/json 的模型架构不匹配:[对象缺少必需的属性(["propertyD"])]
但是当我使用来自 Postman 的相同无效输入调用相同的 API(和阶段)时,验证似乎没有发生,并且请求被代理到 Lambda,只要我注释掉依赖于 propertyD
的代码部分。
这里有什么区别?我应该从客户端传递任何请求 header 吗?我在 AWS 文档中找不到任何内容
最佳答案
回答我的问题-
问题在于请求中使用的 header - Postman 将 JSON 默认为 text/plain
的 Content-Type
,我不得不使用下拉菜单切换到 JSON在 Body 选项卡中使 PostMan 将 Content-Type 设置为 application/json
关注这篇文章似乎解决了问题:https://itnext.io/how-to-validate-http-requests-before-they-reach-lambda-2fff68bfe93b ,虽然它没有解释如何
显然,魔法在于在 HTTP 请求 header
部分下添加 Content-Type
header 的配置,即使 header 已正确设置为application/json
在 PostMan 中。
关于amazon-web-services - APIGateway 在使用 POSTMan 调用时不执行请求验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68336582/