Go to Synthetics canary page, and click on Create canary
We are going to creatae a new canary that will test the PetSearch API responses. Go to /cdk/pet_stack/resources
folder and open the file syn-apicanary.js
in your favorite editor.
Take a look at the code below in the file
const pettypes = ["fish", "bunny", "puppy", "kitten"];
const position = Math.floor(Math.random() ` Math.floor(4));
const requestOptions = {
hostname: '<ALB_HOST_NAME>',
// Example: hostname: 'petsearch-live.us-east-1.elasticbeanstalk.com',
port: 80,
path: '/api/search?pettype='+pettypes[position],
method: 'GET'
}
The PetAdoptions application does not support the PetType fish
, however this code above randomly picks array entries from the pettypes array. There are good chances for it to pick fish
once in a while.
Replace the string <ALB_HOST_NAME>
with the host name of the PetSearch API. You can get this from the CDK output or by going to the ALB console.
Now take a look at the code below which is also part of syn-apicanary.js
req.on('response', (res) => {
log.info(`Status Code: ${res.statusCode}`)
log.info(`Response Headers: ${JSON.stringify(res.headers)}`)
if (res.statusCode !== 200) {
reject("Failed: " + requestOption.path);
}
res.on('data', (d) => {
log.info("Response: " + d.length);
if(d.length <= 2)
{
reject("PetType Invalid - : "+requestOption.path );
}
});
res.on('end', () => {
resolve();
})
});
In this code, you see that the response length is checked, and if the response length is short (<=2) we call the reject()
function which indicates canary executing failure.
Select Upload a script
option and click on Browser files
under Script editor
to upload the canary.js
file. Type in exports.handler
in the Script entry point
textbox under Lambda handler
You can also optionally create an alarm based on the metrics created by Synthetics as shown below.
Under VPC settings
, you can also select the VPC under which you want the canary to be placed on. This is vital if you are testing a non-public facing endpoint. In our case the API endpoint is public facing so you can leave it as it is.
Click Create canary
This will create the canary and start execution. You should be able to see the canary status on the canary home page as shown below
Click the canary name you just created and you should see a screen with execution details for the past executions. The failure runs as in red dots for easier identification. You can select any one of them and go to Logs
tab to see the execution logs.
Since this is an API testing canary which does not have UI, there were no screenshots captured.
Navigate around the Metrics
and Configuration
tabs to see more details about the canary run.