问题描述
我已经配置了我的AWS APIGateway以根据JSON模式验证请求.
I have configured my AWS APIGateway to validate the requests according to a JSON schema.
例如路径/vehicle,其中附加了以下架构:
E.g. the path /vehicle, which has the following schema attached:
{
"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"}
.我想自定义此消息,例如
This works fine. If I submit an invalid request the API responds with a 400 {"message": "Invalid request body"}
. I would like to customize this message, e.g. to
{
"entity": "vehicleType",
"message": "missing"
}
如果我查看来自Gateway的日志,似乎记录了类似的消息(对象缺少必需的属性(["vehicleType"])
).我可以用那个吗?我该如何访问?
If I take a look at the logs from the Gateway it seems that a similar message is logged (object has missing required properties (["vehicleType"])
). Can I use that one? How can I access it?
日志:
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网关有可能吗?
Is this possible with the API Gateway?
推荐答案
是的,您想要的是 $ context.error.validationErrorString
就像@Bajwa所说的那样-您需要自定义GatewayReponse模板.如果您使用的是如下所示的云形成:
Like @Bajwa said -- you need to customize the GatewayReponse template. If you're using cloud formation that looks like this:
"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"
}
}
如果您违反了请求正文验证器,则会看到以下内容:
If you violate the request body validator you'll see something like this:
{
"error": {
"message":" "Invalid request body"",
"errors":"[string \"1\" is too short (length: 1, required minimum: 10)]"
}
这不是完美的-某些消息是含糊的,如果有人知道如何添加例如引起违规的属性名称,那将是很好的.
It's not perfect -- some of the messaging is vague, would be nice if anyone knows how to for example add the property name that caused the violation.
这篇关于AWS ApiGateway自定义请求验证响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!