Gateway Response Customization in case of request validation failure

Viewed 12

Background

I am trying to validate the request (body and parameters) in the openapi specification file, which I in turn, use to create my integrations (to AWS LAMBDA functions) from the AWS API Gateway. I am using the aws extensions - x-amazon-apigateway-request-validator to perform the schema validation of the request body.

Requirement

When there is a schema validation failure, I intend to catch the same and customize the error message using the approach documented in this article.

As it can be observed from the article, the custom response is constructed as an application/json type and the error response template has been defined. However, I have defined an "ErrorResponseMessage" model in my openapi specification file and I would like to use the same in the scenario I have explained above.

I am not sure how this can be achieved. Any help on this would be highly appreciated.

Below are the relevant sections from my openapi file:

x-amazon-apigateway-request-validators:
  request-body-only: 
    validateRequestBody: true
    validateRequestParameters: false
  params-only:
    validateRequestBody: false
    validateRequestParameters: true  
  full:
    validateRequestBody: true
    validateRequestParameters: true

paths:
  /test:
    post:
      x-amazon-apigateway-request-validator: request-body-only
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateRequest'
      responses:
        "400":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessageResponse'
components:
    ErrorMessageResponse:
      type: object
      properties:
        statusCode:
          type: integer
          format: int32
          example: 400
        message:
          type: string
          example: Unexpected error.
        errors:
          type: array
          items:
            $ref: '#/components/schemas/ErrorMessage'
    ErrorMessage:
      type: object
      properties:
        code:
          type: string
          example: UnexpectedError
        message:
          type: string
          example: Unexpected error.
        type:
          type: string
        id:
          type: string

I would like to catch the validation errors and transform the error response on the API Gateway itself like below using the aws open-api extensions (to be added in the openapi specification file)

x-amazon-apigateway-gateway-responses: 
  BAD_REQUEST_BODY: 
    statusCode: '400'
    responseTemplates: 
      application/json:
        schema:
          $ref: '#/components/schemas/ErrorMessageResponse'     

As one can notice, the intention here is to transform the error response to "ErrorMessageResponse" but I am not sure how I can achieve it.

0 Answers
Related