amazon-web-services - AWS Api Gateway 自定义请求验证响应

标签 amazon-web-services validation aws-api-gateway

我已将 AWS APIGateway 配置为根据 JSON 架构验证请求。

例如。路径/vehicle,附加了以下架构:

{
   "type":"object",
   "properties":{
      "licensePlate":{
         "pattern":"[A-Za-z]{1,3} [A-Za-z]{1,2} \\d{1,4}",
         "type":"string"
      },
      "vehicleType":{
         "type":"string",
         "enum":[
            "Truck",
            "Trailer"
         ]
      }
   },
   "required":[
      "licensePlate",
      "vehicleType"
   ]
}

这工作正常。如果我提交无效请求,API 会以 400 {"message": "Invalid request body"} 响应。 .我想自定义此消息,例如到
{
  "entity": "vehicleType",
  "message": "missing"
}

如果我查看网关的日志,似乎记录了类似的消息( object has missing required properties (["vehicleType"]) )。我可以用那个吗?我怎样才能访问它?

日志:
Execution log for request test-request
Thu Feb 01 13:12:18 UTC 2018 : Starting execution for request: test-invoke-request
Thu Feb 01 13:12:18 UTC 2018 : HTTP Method: POST, Resource Path: /vehicle
Thu Feb 01 13:12:18 UTC 2018 : Method request path: {}
Thu Feb 01 13:12:18 UTC 2018 : Method request query string: {}
Thu Feb 01 13:12:18 UTC 2018 : Method request headers: {}
Thu Feb 01 13:12:18 UTC 2018 : Method request body before transformations: {
    "licensePlate": "HH AB 123"
}
Thu Feb 01 13:12:18 UTC 2018 : Request body does not match model schema for content type application/json: [object has missing required properties (["vehicleType"])] 
Thu Feb 01 13:12:18 UTC 2018 : Method completed with status: 400

这可以通过 API 网关实现吗?

最佳答案

是的,您想要的是$context.error.validationErrorString

就像@Bajwa 所说的——您需要自定义 GatewayReponse 模板。如果您使用的是如下所示的云形成:

"GatewayResponse": {
  "Type": "AWS::ApiGateway::GatewayResponse",
  "Properties": {
    "ResponseParameters": {
      "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
      "gatewayresponse.header.Access-Control-Allow-Headers": "'*'"
    },
    "ResponseTemplates": {
      "application/json": "{\"error\":{\"message\":\"$context.error.messageString\",\"errors\":\"$context.error.validationErrorString\"}"
    },
    "ResponseType": "BAD_REQUEST_BODY",
    "RestApiId": {
      "Ref": "YouRestApiResource"
    },
    "StatusCode": "400"
  }
}

如果您违反了请求正文验证器,您将看到如下内容:
{
  "error": {
    "message":" "Invalid request body"",
    "errors":"[string \"1\" is too short (length: 1, required minimum: 10)]"
}

这并不完美——有些消息是模糊的,如果有人知道如何添加导致违规的属性名称,那就太好了。

关于amazon-web-services - AWS Api Gateway 自定义请求验证响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48563707/

相关文章:

amazon-web-services - AWS EC2 策略无法更改用户数据

amazon-web-services - 在 describe-vpcs 中按标签过滤的正确语法是什么?

php - 如何保护 $_SERVER ['PHP_SELF' ]?

Matlab 机器学习训练、验证、测试分区

api - 对 API Gateway 使用 AWS 资源还是 Swagger API 导入?

c# - 使用 .NET 连接到亚马逊

amazon-web-services - AWS 服务使用 Java API 进行语音到文本

使用 FOR 循环的 Javascript 表单验证

aws-api-gateway - 如何强制 API Gateway 不解码参数或 CloudSearch 期望解码的斜杠?

amazon-web-services - Go lang 中的 AWS API Gateway 客户端证书