如何在AWS CDK中修改API Gateway默认BAD_REQUEST_BODY响应模板?
Customizing API Gateway's BAD_REQUEST_BODY Response Template
Absolutely! You can totally customize API Gateway's default BAD_REQUEST_BODY response template to return that exact validation error format you're after. Here's a step-by-step breakdown of how to make it happen:
- First, head over to your API Gateway console, locate the target API, and navigate to the specific resource and method you want to configure.
- Go to the Integration Response settings for that method (note: you’ll also want to make sure the corresponding 400 status code is enabled in Method Response first, if it isn’t already).
- In the Integration Response section, find the entry for HTTP Status Code 400—if there isn’t one, click "Add integration response" and select 400 from the dropdown.
- Expand the 400 response settings, then scroll down to the Mapping Templates section.
- Click "Add mapping template", enter
application/jsonas the Content-Type, and check the box for "Never send empty models" to ensure your custom response is always sent. - Paste this template into the editor box:
{ "message": "$context.error.messageString", "validationErrors": "$context.error.validationErrorString" } - Save all your changes, then redeploy your API to a stage—this is crucial, as the new template won’t take effect until you deploy.
A few quick notes to keep in mind:
- Make sure request validation is enabled for your API (like using a JSON Schema to validate the request body). Without this,
$context.error.validationErrorStringwill be empty, since there won’t be any validation errors to capture. - If
$context.error.validationErrorStringreturns multiple errors separated by commas, you can do basic string manipulation in the VTL template if you want to format it as an array. For more complex transformations, you might need to use a Lambda integration to process the error before sending the response. - Test it out by sending a request that fails your validation rules—you should see your custom JSON response with the error details.
内容的提问来源于stack exchange,提问作者milan
相关产品推荐
相关产品推荐

