Hands-On Serverless Applications with Kotlin
上QQ阅读APP看书,第一时间看更新

Integration testing

Once the API Gateway is configured and integrated with Lambda, one can test it in sandbox mode.

Note that the function is not currently deployed or configured to receive triggers from the outside world. To expose the API to the outside world, it has to be deployed on something called the API Gateway Stage. We will explore that in future sections.

To test in the sandbox mode, you have to click on the Test link, as shown in the following screenshot:

The preceding screenshot shows the test of the positive flow of the API, invoking the Gateway with a request that has a string in the body with the value API GATEWAY. The response is as expected: Hello, API GATEWAY. The following screenshot shows the test of the negative flow via the API Gateway, sending an unparseable response body. As expected, it throws a JSONMappingException:

The preceding screenshot shows that the invalid input error is not handled correctly. This is not the best practice for a production-grade app. A production-grade app has to validate its input parameters and return an appropriate error code.

To configure request validation with API Gateway, one can go to the Method Request configuration stage of the integration and apply a proper request validation so that incorrect requests are not passed to the backend Lambda function.

To do so, define a model using the JSON schema, which models the input to the API. Then, attach this model to the method request for the API.

Define a model named GreetingInput. This definition takes in a model schema in JSON Schema - Draft 04 format.

Because our input is a simple string, the JSON schema definition is as follows:

{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "string"
}

The following screenshot shows the steps taken to create the model in the console:

Once the model is created, it has to be attached to the request body via the Method Request configuration section. The content type is application/json.

The following screenshot shows the details  for attaching the model GreeterInput as the request body to the /greeter API.

Once this is done, you can test the integration by clicking on Test. As expected, the error code for an invalid input (which is not a simple string) is 400: