I have created an API Gateway requestValidator to validate the body of the incoming request.
I have used JsonSchemaVersion.DRAFT4
to create my models.
The validator works fine but the message the error message I receive is always "Invalid request body" and I wish to have a more informative message. Like which field exactly is invalid and the reason if possible.
Here is an example of the model I have.
const CenterPointModel = {
title: 'CenterPoint Data Model',
schema: JsonSchemaVersion.DRAFT4,
type: JsonSchemaType.OBJECT,
properties: {
type: {
type: JsonSchemaType.STRING,
enum: [GeometryType.Point]
},
coordinates: { type: JsonSchemaType.ARRAY }
},
required: ['type', 'coordinates']
};
export const MapModel = (api: RestApi) => {
return api.addModel('RequestBodyModel', {
contentType: 'application/json',
modelName: 'RequestBodyModel',
schema: {
schema: JsonSchemaVersion.DRAFT4,
title: 'Map configuration Data Model',
type: JsonSchemaType.OBJECT,
properties: {
centerPoint: CenterPointModel,
displayRangeMin: { type: JsonSchemaType.NUMBER },
displayRangeMax: { type: JsonSchemaType.NUMBER },
},
required: [
'centerPoint',
'displayRangeMin',
'displayRangeMax',
]
}
});
};
I have tried out adding the error: "Type must be Point"
under enum: [GeometryType.Point]
but it didn’t work.
I also found answers related to patterns and limit but this is not what I’m looking for.
I’m looking to identify the invalid field and if possible state why is it invalid.
2
Answers
I have been looking at it in the wrong way.
In
JsonSchemaVersion.DRAFT4
to view error messages, it is not done using theerror
attribute in theschema
object but in the main stack create a newGatewayResponse
The following code worked for me:You can modify the mapping template of the standard response for 400: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-gatewayResponse-definition.html
You can add the
$context.error.validationErrorString
information into the response body.