Return proper JSON validation errors from API Gateway Response

0

I'm working on developing a REST Api. I have created a model for one of my resources and am using it to validate a post request. I would like to return any validation errors as a properly formed JSON string.

I have a Gateway Response for Bad Request Body defined like this:

{
    "message": $context.error.messageString, 
    "errors":"$context.error.validationErrorString"
}

This works, but the issue I have is that what is returned by $context.error.validationErrorString is not a valid JSON string. If I submit the request with no information, the response returned returned is

{
  message: 'Invalid request body',
  errors: '[object has missing required properties (["contactEmail","contactMessage","contactName","contactReason","contactSubject"])]'
}

The string returned in the errors property is not valid JSON. If in my calling client I try to parse the error string has JSON it fails to parse.

So, my question is, is there a way with Gateway Responses to get the validation error string as a properly formed JSON string? If not, what is the recommended way to handle this? Why isn't this string a properly formed JSON string since it would seem that its intent is to be returned in a JSON response.

Incidentally, if it matters, this API end point is proxying to a Lambda function, but I want API Gateway to do the validation before the Lambda function is called.

1 Answer
1
Accepted Answer

The $context.error.validationErrorString parameter is a string containing a detailed validation error message [1]. This may be proper JSON or not, depending on the validation errors.

Unfortunately, the customization of the validation error is currently not supported in API Gateway. There is also no current way to programmatically access the information obtained from "$context.error.validationErrorString" parameter within the API Gateway.

A workaround would be for the logic in the application or workflow (the client) that is responsible for processing the validation error message, will have to format the string as needed i.e stripping the parenthesis and square brackets from the $context.error.validationErrorString parameter response.

A feature request is open with regards to the format of the $context.error.validationErrorString parameter response not being a proper JSON string at all times. No timelines are available as to when this may be implemented.

Take care!

Resources:

[1] https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference

SUPPORT ENGINEER
James_H
answered 3 months ago
profile picture
MODERATOR
Chris_G
reviewed 3 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions