Examples
To execute your scripted API monitors using node-fetch make sure your script's syntax uses the variable $http
to interact with and page respectively.
Warning: Scripted API does not support .then
notation. Please use async
/await
syntax instead.
Snippets
Here are some common snippets that you can use in your scripted API monitors. Please note that these snippets are just examples and you can modify them as per your requirements. For any additional help, please refer to the node-fetch documentation or reach out to our support team.
Configure request options
You can configure request options such as headers, method, and body for your API requests. Define these options in a separate object and pass them to the $http
method when making the request.
Declare a variable (such as options) to store your node-fetch options object.
// Define the options for the fetch request
const options = {
method: 'GET', // Use GET method (can be 'POST', 'PUT', 'DELETE', etc.)
headers: { // Define custom headers
'Accept': 'application/json',
'Authorization': 'Bearer your-token-here'
},
body: null, // No body for GET request; for POST, you could use JSON.stringify({ key: value })
redirect: 'follow', // Automatically follow redirects
signal: null, // Optionally pass an AbortSignal to cancel the request
follow: 10, // Maximum number of redirects to follow
compress: true, // Enable gzip/deflate content encoding support
size: 1024 * 1024, // Set a maximum response body size of 1MB
agent: null, // Not using a custom agent (can specify http.Agent or https.Agent)
highWaterMark: 16 * 1024, // The maximum number of bytes to store in the internal buffer (16KB)
insecureHTTPParser: false // Use the default secure HTTP parser
};
Send a GET request
To make a GET request, use the $http.get method to submit your request. Define your request options, make your request using $http.get, then validate the response to ensure your endpoint is returning the correct results.
The following example demonstrates how you can:
- Handle retries and timeouts for a GET request
- Parse the json response body.
- Assert on the response status code and data count.
/**
* Script Name: Advanced Example
* Author: Boltic
* Version: 1.0
*/
const assert = require('assert');
// The URL for the API endpoint to get users data from ReqRes
const URL = 'https://reqres.in/api/users?page=1';
// Define headers, including any necessary custom headers
const headers = {
"Content-Type": "application/json"
};
// Retry mechanism parameters
const maxRetries = 3;
const retryDelay = 1000; // in milliseconds
// Function to make the request with retry logic
async function getWithRetry(url, options, retries) {
try {
const response = await $http(url, options);
// Check if the response status is one of the retriable status codes
const retriableStatusCodes = [408, 429, 500, 502, 503, 504];
if (retriableStatusCodes.includes(response.status)) {
throw new Error(`Retriable status code: ${response.status}`);
}
// Check if the response status is OK (200)
assert.equal(response.status, 200, "Expected HTTP status code 200");
console.log("Request Status Code:", response.status);
// Parse the JSON from the response
const jsonData = await response.json();
// Log the parsed JSON to the console
console.log("Parsed JSON data:", jsonData);
// Check if the returned data count is more than 1
const dataCount = jsonData.data.length;
assert(dataCount > 1, `Expected data count to be more than 1, but got ${dataCount}`);
console.log("Data Count:", dataCount);
} catch (error) {
// If retries are left, retry the request
if (retries > 0) {
console.log(`Request failed with error: ${error.message}. Retrying... (${maxRetries - retries + 1}/${maxRetries})`);
await new Promise(res => setTimeout(res, retryDelay)); // Wait before retrying
return getWithRetry(url, options, retries - 1);
} else {
// If no retries are left, throw the error
console.log(`Request failed after ${maxRetries} attempts: ${error.message}`);
}
}
}
// Define options for the request including headers and timeout
const options = {
method: 'GET',
headers: headers,
timeout: 10000, // Set a global timeout of 10000 milliseconds for the request
};
// Call the getWithRetry function with the defined options and retry mechanism
await getWithRetry(URL, options, maxRetries);
Send a POST request
To make a POST request, use the $http.post method to submit your request. Define your request options, make your request using $http.post, then validate the response to ensure your endpoint is returning the correct results.
The following example demonstrates how you can:
- Handle retries and timeouts for a POST request
- Create a JSON payload to send in the request body
- Assert on the response status code
/**
* Script Name: Advanced Example
* Author: Boltic
* Version: 1.0
*/
const assert = require('assert');
// The URL for the API endpoint to create a user on ReqRes
const URL = 'https://reqres.in/api/users';
// The JSON payload to send in the POST request
const payload = {
name: "morpheus",
job: "leader"
};
// Define headers, including any necessary custom headers
const headers = {
"Content-Type": "application/json"
};
// Retry mechanism parameters
const maxRetries = 3;
const retryDelay = 1000; // in milliseconds
// Function to make the POST request with retry logic
async function postWithRetry(url, options, retries) {
try {
const response = await $http(url, options);
// Check if the response status is one of the retriable status codes
const retriableStatusCodes = [408, 429, 500, 502, 503, 504];
if (retriableStatusCodes.includes(response.status)) {
throw new Error(`Retriable status code: ${response.status}`);
}
// Check if the response status is 200 (OK)
assert.equal(response.status, 200, "Expected HTTP status code 200 (OK)");
console.log("Request Status Code:", response.status);
// Parse the JSON from the response
const jsonData = await response.json();
// Log the parsed JSON to the console
console.log("Parsed JSON data:", jsonData);
} catch (error) {
// If retries are left, retry the request
if (retries > 0) {
console.log(`Request failed with error: ${error.message}. Retrying... (${maxRetries - retries + 1}/${maxRetries})`);
await new Promise(res => setTimeout(res, retryDelay)); // Wait before retrying
return postWithRetry(url, options, retries - 1);
} else {
// If no retries are left, throw the error
console.log(`Request failed after ${maxRetries} attempts: ${error.message}`);
}
}
}
// Define options for the POST request including method, headers, and body
const options = {
method: 'POST',
headers: headers,
body: JSON.stringify(payload),
timeout: 10000, // Set a global timeout of 10000 milliseconds for the request
};
// Call the postWithRetry function with the defined options and retry mechanism
await postWithRetry(URL, options, maxRetries);
Validate results
To validate your results, import the assert
module to define your test case. Call an assert
method to validate your endpoint's response. If any assert
functions fail, the entire monitor will be considered a failed check. This may trigger alert notifications and affect your metrics.
Use the assert
module to validate your results, and use console.log()
to log results to the synthetic's console
const assert = require('assert');
// Define the URL and payload
const URL = 'https://reqres.in/api/users';
const payload = {
name: "morpheus",
job: "leader"
};
// Define headers
const headers = {
'Content-Type': 'application/json'
};
// Define options for the POST request including method, headers, and body
const options = {
method: 'POST',
headers: headers,
body: JSON.stringify(payload),
};
// Send the POST request
$http(URL, options)
.then(response => response.json()) // Parse the JSON from the response
.then(jsonData => {
// Log the parsed JSON to the console
console.log("Parsed JSON data:", jsonData);
// Validate if the response contains an 'id' field
assert.ok(jsonData.id, 'Expected the response to contain an id field');
// Optionally log success if assertion passes
console.log('Validation successful: id field exists in the response');
})
.catch(error => {
// Handle any errors that occurred during the fetch or assertion
console.log(`Request failed: ${error.message}`);
});