Write Synthetics API tests

Use New Relic Synthetics API tests to monitor your API endpoint to ensure it is functioning correctly. New Relic uses the http-request module internally to make HTTP calls to your endpoint and validate the results.

This document contains example functions showing how to use the $http object to submit your request. For detailed documentation on the options available for this object, see the http-request readme.

To view and share other API test examples, visit the Synthetics scripts section in New Relic's Explorer's Hub.

Use API http-request module

API tests are powered by the http-request module, which is available through the $http object. Once each frequency interval, Synthetics queries your endpoint from each of your selected locations. For instructions on creating a monitor, see Adding monitors.

This document describes how to define metadata for your request, make a GET request, make a POST request, and how to validate the results.

After a maximum run time of three minutes, Synthetics manually stops the script.

screen-synthetics-api-test-ide.png
synthetics.newrelic.com > Add monitor > API Test: The script editor suggests functions, selectors, and other elements to simplify scripting commands (available in GitHub).

Configure request options

Begin your script by defining metadata such as URL endpoint, API key, or authentication credentials. Declare a variable (such as options) and include your optional metadata inside the variable.

For a full list of supported request options, see request(options, callback) in the http-request documentation on GitHub.

If you are setting values in the agentOptions property of the request options object, the agent property in the request options object will need to be set to $globalAgents.https or $globalAgents.http to ensure your HTTP requests use the instrumented global agent.

Using optional metadata
//Declare optional metadata
var options = {
        //Specify the endpoint URL
        url: 'https://api-endpoint.example.com',
        //Specify optional headers
        headers: {
                'Endpoint-Key': 'uqNTC57Phe72pnnB8JuJmwAr7b09nKSKSz',
                'Additional-Header': 'Additional-Header-Data'
        }
};
Using agentOptions

This example uses agentOptions.

//Declare optional metadata
var options = { 
        //Specify the endpoint URL 
        url: 'https://api-endpoint.example.com', 
        //Specify optional headers 
        headers: { 
                'Endpoint-Key': 'uqNTC57Phe72pnnB8JuJmwAr7b09nKSKSz', 
                'Additional-Header': 'Additional-Header-Data' 
        }
        //Specify global agent as the http agent
        agent: $globalAgents.https
        //Specify http agent options
        agentOptions: {
                'rejectUnauthorized': false
        }
};

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.

Insights GET example

This example queries the Insights API by using GET:

//Define your authentication credentials
var myAccountID = '{YOUR_ACCOUNT_ID}';
var myQueryKey = '{YOUR_QUERY_KEY}';
var options = {
    //Define endpoint URI
    uri: 'https://insights-api.newrelic.com/v1/accounts/'+myAccountID+'/query?nrql=SELECT%20average(amount)%20FROM%20SyntheticsEvent',
    //Define query key and expected data type.
    headers: {
    'X-Query-Key': myQueryKey,
    'Accept': 'application/json'
}
};

//Define expected results using callback function.
function callback (err, response, body){
//Log JSON results from endpoint to Synthetics console.
 console.log(JSON.parse(body)); 
 console.log('done with script');
}

//Make GET request, passing in options and callback.
$http.get(options,callback);

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.

Insights POST example

This example POSTs a custom Insights event containing static integers:

//Define your authentication credentials.
var myAccountID = '{YOUR_ACCOUNT_ID}';
var myInsertKey = '{INSERT_KEY}';
//Import the 'assert' module to validate results.
var assert = require('assert');

var options = {
    //Define endpoint URL.
    url: "https://insights-collector.newrelic.com/v1/accounts/"+myAccountID+"/events",
    //Define body of POST request.
    body: '[{"eventType":"SyntheticsEvent","integer1":1000,"integer2":2000}]',
    //Define insert key and expected data type.
    headers: {
        'X-Insert-Key': myInsertKey,
        'Content-Type': 'application/json'
        }
};

//Define expected results using callback function.
function callback(error, response, body) {
    //Log status code to Synthetics console.
    console.log(response.statusCode + " status code")
    //Verify endpoint returns 200 (OK) response code.
    assert.ok(response.statusCode == 200, 'Expected 200 OK response');
    //Parse JSON received from Insights into variable.
    var info = JSON.parse(body);
    //Verify that `info` contains element named `success` with a value of `true`.
    assert.ok(info.success == true, 'Expected True results in Response Body, result was ' + info.success);
    //Log end of script.
    console.log("End reached");
}

//Make POST request, passing in options and callback.
$http.post(options, callback);

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.

Synthetics does not allow thrown exceptions. Thrown exceptions result in script failure. Use the assert module to validate your results, and use console.log() to log results to the Synthetics console.

Insights validation example

This example POSTs to the Insights API, then validates that the response is {"success":true}:

//Define your authentication credentials.
var myAccountID = '{YOUR_ACCOUNT_ID}';
var myInsertKey = '{INSERT_KEY}';
//Import the `assert` module to validate results.
var assert = require('assert');

var options = {
    //Define endpoint URL.
    url: "https://insights-collector.newrelic.com/v1/accounts/"+myAccountID+"/events",
    //Define body of POST request.
    body: '[{"eventType":"SyntheticsEvent","integer1":1000,"integer2":2000}]',
    //Define insert key and expected data type.
    headers: {
        'X-Insert-Key': myInsertKey,
        'Content-Type': 'application/json'
        }
};

$http.post(options, function(error, response, body) {
    //Log status code to Synthetics console. The status code is logged before the `assert` function, 
    //because a failed assert function ends the script.
    console.log(response.statusCode + " status code")
    //Call `assert` method, expecting a `200` response code.
    //If assertion fails, log `Expected 200 OK response` as error message to Synthetics console.
    assert.ok(response.statusCode == 200, 'Expected 200 OK response');  
        var info = JSON.parse(body);
    //Call `assert` method, expecting body to return `{"success":true}`.
    //If assertion fails, log `Expected True results in Response Body,` plus results as error message to Synthetics console. 
    assert.ok(info.success == true, 'Expected True results in Response Body, result was ' + info.success);
});

For more help

Recommendations for learning more: