skip to Main Content

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


  1. Chosen as BEST ANSWER

    I have been looking at it in the wrong way.

    In JsonSchemaVersion.DRAFT4 to view error messages, it is not done using the error attribute in the schema object but in the main stack create a new GatewayResponse The following code worked for me:

    const BadRequestBodyTemplate: string = JSON.stringify({
      message: '$context.error.validationErrorString'
    });
    
    const badReqBodyGatewayRespProps: GatewayResponseProps = {
              restApi: featuresApi,
              type: ResponseType.BAD_REQUEST_BODY,
              statusCode: HttpStatusCode.BadRequest,
              templates: {
                'application/json': BadRequestBodyTemplate
              }
            };
            new GatewayResponse(this, ApiGatewayResponses.BadRequestBody, badReqBodyGatewayRespProps);
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search