AWS ApiGateway自定义请求验证响应

时间:2018-02-01 13:16:16

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

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

E.g。路径/车辆,附有以下架构:

{
   "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"
}

如果我查看来自Gateway的日志,似乎会记录类似的消息(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网关实现吗?

2 个答案:

答案 0 :(得分:2)

是的,您想要的是$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)]"
}

这不是完美的-某些消息是含糊的,如果有人知道如何添加例如引起冲突的属性名称,那将是很好的。

答案 1 :(得分:1)

如果请求有效负载无效,您将看到相同的消息:

{
  "message": "Invalid request body"
}
如果请求有效载荷格式有效且参数格式无效,则

API网关包含更多详细信息。

从下面的链接中查看更多详细信息,尤其是底部。

Test Basic Request Validation in API Gateway

但您可以通过自定义网关响应在响应消息中进行一些自定义。 您可以自定义Bad Request Body 400

{" message":$ context.error.messageString,"提示":"检查所需数量的参数或参数允许的类型和长度。"}

然后您将看到以下格式的消息。

{
    "message": "Invalid request body",
    "Hint": "Check required number of parameters or parameters allowed type and length."
}

请参阅hot以从附加的屏幕截图更新Body Mapping Template。 (APIGateway / Gateway响应)。 enter image description here