Getting Started with the ThousandEyes API

Introduction

The ThousandEyes API enables programmatic access to ThousandEyes features and data, allowing you to integrate ThousandEyes with third-party systems and to automate tasks such as creating and modifying tests or retrieving test data. The ThousandEyes API is a RESTful API that uses standard HTTP methods and response codes.

In this guide, you will learn the basics of using the ThousandEyes API, including authentication and permission requirements, the different available endpoints, and example use cases with implementations.

The complete developer reference is available at ThousandEyes API v7.

Prerequisites

To get the most out of this guide, you need the following prerequisites:

  • A basic understanding of REST APIs and HTTP.

  • Some familiarity with programming concepts and a programming language of your choice; or an HTTP client such as curl or Postman.

Because the ThousandEyes API enables you to interact with the entire ThousandEyes platform, we recommend that you complete the Getting Started guides for the features and data you want to consume via the API.

API User Requirements

To use the ThousandEyes API, you must have the following:

  • Your user role must have the API access permission. The three built-in roles (Organization Admin, Account Admin, and Regular User) include this permission by default.

  • You must have a user API token generated by the ThousandEyes platform to authenticate your requests.

Authentication

The ThousandEyes API uses the HTTP bearer authentication scheme . Your API bearer token can be managed in Account Settings > Users and Roles > Profile.

Tokens are only displayed when you create or re-create them. Ensure that you safely store your token (for example, in a password manager), as you will not be able to view the token again in the ThousandEyes platform after generating it. If you lose or forget your token, you can regenerate a new token in Account Settings > Users and Roles > Profile.

The OAuth bearer token allows you to authenticate to the ThousandEyes API using a token, without providing a username. To authenticate with your OAuth bearer token, you must include it in the Authorization header of your requests. The value of the header must be Bearer <your-oauth-bearer-token-here>.

The following example shows OAuth bearer token authentication with curl:

curl https://api.thousandeyes.com/v7/status \
  --header "Authorization: Bearer f537f4ac-2921-3199-bbab-d5a43f1c2b60"

To authenticate in Postman with an OAuth bearer token:

  1. In the Authorization tab, select the Bearer token type.

  2. In the Token field, enter your OAuth bearer token.

Making Requests

To use the ThousandEyes API, send an HTTP request to an endpoint at api.thousandeyes.com. The URL for your request should be of the form https://api.thousandeyes.com/[version]/[endpoint]. The current production version of the API is v7.

Before exploring the capabilities of the various endpoints, read the following sections on specifying an account group.

Specifying an Account Group

API requests are handled within the context of an account group. If your user is assigned to only one account group, you do not need to specify an account group in your requests.

If your user is assigned to multiple account groups, the default account group context is your login account group. To access a different account group, you must specify the account group ID in your API request by using the aid URL query parameter.

In the two example curl commands below, the first returns a list of all tests in the login account group, and the second returns a list of all tests in the account group with ID 123456. Note: For the sake of brevity, authentication is omitted from this example.

curl https://api.thousandeyes.com/v7/tests

curl https://api.thousandeyes.com/v7/tests?aid=123456

API Endpoints and Use Cases

Administrative and Account Management

One common use case of the ThousandEyes API is for managing your account groups and users. For example, you can easily create users in bulk, reassign users to different account groups, or programmatically create a new role and assign it to multiple users.

Cloud and Enterprise Agents

You can use the ThousandEyes API for managing your Cloud and Enterprise Agents and tests, and for retrieving test result data.

Configuration and Management

Test Data

As described in Getting Started with Tests, most Cloud and Enterprise Agent tests are composed of multiple layers. Using the API, you can retrieve test data from the individual layers that comprise the test.

The complete list of endpoints for Cloud and Enterprise Agent test data is available in the Test Data page of the developer reference. Using these endpoints, you can retrieve metrics from the following test layers:

  • Routing - BGP: BGP metrics, BGP routes

  • Network: End-to-end (“overview”), path visualization, and detailed path trace

  • Web: FTP server, HTTP server, page load and waterfall, transaction and waterfall

  • DNS: DNS server, DNS trace, DNSSEC

  • Voice: SIP server, RTP stream

Endpoint Agents

Use the Endpoint Agent APIs to manage your fleet of agents and configure your scheduled tests and dynamic tests.

Configuration and Management

Test, Network, and Session Data

As described in the Endpoint Agents article, ThousandEyes Endpoint Agents collect measurements in multiple ways: scheduled synthetic tests, dynamic tests, real user tests sessions, and local network topology. You can use the ThousandEyes API to retrieve Endpoint Agent data from each of these areas; see the Endpoint Test Results page in the developer reference.

  • Scheduled Test Data: HTTP server, network end-to-end, path visualization, and detailed path trace

  • Dynamic Test Data: Network end-to-end, path visualization, and detailed path trace

  • Real User Test Data: Real user test list and details, visited page list and details, network sessions list

  • Local Network Data: Network topology list and details

Alerts

You can use the API to retrieve the list of all active alerts and the details for individual alerts. You can also manage your alert rules and alert suppression windows.

Dashboards

You can also retrieve the data for a dashboard widget using the retrieve dashboard widget data endpoint.

Example Code Snippets

One of the advantages of a RESTful API is its flexibility and versatility. A well-designed API allows developers to integrate it into their applications in many different ways, depending on their specific needs and requirements. This section provides a few examples of how you might use the ThousandEyes API, to give you an idea of its potential applications.

It's important to note that the examples provided below are only a small subset of the many ways you could use this API. Your particular use case may be quite different from those described, but these examples will help you understand the possibilities and inspire you to create your own integrations.

Additionally, please be aware that the code implementations provided below are strictly examples and are not intended for production use. They may not follow best practices, and may not be optimized for performance or security. They are simply meant to illustrate how you might interact with the ThousandEyes API in a particular context.

With that in mind, let's dive into some examples of how you might use this ThousandEyes API in practice.

Getting a List of Cloud Agent IPs for Automating Firewall Rules

Cloud Agents are generally used to monitor public internet-facing web applications, but occasionally you may test a target that only allows traffic from explicitly allowed sources. In this case, you need to add the Cloud Agents' IP addresses to your security rule access control list, to allow the test traffic to reach the target server. Using the ThousandEyes API, you can easily retrieve the IP addresses for any Cloud Agents so that you can add them to your allow-list.

This example uses two CLI utilities, curl and jq, to request and parse the list of agents and their respective IP addresses. Additionally, this example demonstrates that you do not need programming knowledge to interact with the ThousandEyes API.

First, use curl to make a request to the /v7/agents endpoint and write the response to a file:

curl -o agents.json https://api.thousandeyes.com/v7/agents \
          -H "Authorization: Bearer YOUR-OAUTH-BEARER-TOKEN-HERE"

This will create a file named agents.json in the current working directory where you ran the curl command. The file contains a JSON object with a key named agents mapped to a list of objects representing the agents, like the excerpt below:

{
    "agents": [
    {
        "agentId": 3,
        "agentName": "Singapore",
        "agentType": "Cloud",
        "countryId": "SG",
        "targetOnly": 0,
        "ipAddresses": [
            "64.29.136.162",
            "64.29.136.173",
             ...
           ]
        }
  ]
}

Now that you have retrieved the agent data from the ThousandEyes API, you can parse or post-process it to meet your requirements. For example, you can use the jq utility to read the agents.json file and extract three fields: the agent ID, the agent name, and the agent’s IP addresses.

jq -r '.agents[] | [.agentId, .agentName, .ipAddresses|tostring] ' agents.json

The output from the jq command should look something like this:

[
   "3",
   "Singapore",
   "[\"64.29.136.162\",\"64.29.136.173\", ...]"
]

You can also use jq to filter the response. For example, you can include only specific agents in the output:

jq -r '.agents[] | select (.agentName | IN("Singapore", "Boston, MA")) | [.agentId, .agentName, .ipAddresses|tostring] ' agents.json

Or, you can use jq to format the JSON as a CSV file, like so:

jq -r '.agents[] | [.agentId, .agentName, .ipAddresses|tostring] | @csv ' agents.json > agents.csv

Exporting Test Data to a CSV File

Retrieving test data is a common use case for the ThousandEyes API. For example, you may want to perform some data analysis on the test results in the tool of your choice, or you need to archive test data longer than the ThousandEyes platform data retention provides, or you collect and aggregate all of your observability data in a centralized data store.

The following code snippet shows how to request, parse, and output the network latency for all agents in a single test over the last one hour. This example uses the Python programming language and the open-source requests package for making HTTP requests to the API server, but you may use whatever language and HTTP client package you prefer.

# Import standard modules
import csv
import json
  
# Import third-party HTTP client package
import requests
  
### Define HTTP request values
OAUTH_BEARER_TOKEN = "YOUR-OAUTH-BEARER-TOKEN-HERE"
TEST_ID = 123456

# Make the HTTP request to the /v7/test-results/{testId}/network endpoint, including
# the Oauth bearer token and specifying the response must be JSON format
resp = requests.get(
  f"https://api.thousandeyes.com/v7/test-results/{TEST_ID}/network?window=60m",
  headers={"Authorization": f"Bearer {OAUTH_BEARER_TOKEN}"},
)
resp_body = resp.json()

# Parse the response JSON to store the metrics by test round so we can
# later write each round as a row in the CSV file
agent_names = set()
data_by_round = {}
metrics = resp_body["results"]
for metric in metrics:
        if metric["roundId"] not in data_by_round:
                data_by_round[metric["roundId"]] = {}
        agent_names.add(metric["agent"]["agentName"])
        data_by_round[metric["roundId"]][metric["agent"]["agentName"]] = metric["avgLatency"]

# Write the data to a CSV file
agent_names = list(agent_names)
with open("test_data.csv", "w") as f:
        csv_file = csv.writer(f)
        csv_file.writerow(["Round ID", *agent_names])
        for roundId, metrics in data_by_round.items():
                csv_file.writerow([roundId, *[metrics[agent] for agent in agent_names]])

Change the Interval of a Cloud and Enterprise Agent Test

The test configuration endpoints are useful whenever you need to create or re-configure a large number of tests, or when you integrate ThousandEyes with an automation pipeline such as Continuous Integration / Continuous Delivery. This example demonstrates how to programmatically re-configure a Cloud and Enterprise Agent test using the JavaScript programming language and the open-source node-fetch package for making HTTP requests.

In the code snippet below, the testing interval of a given test is toggled between 10 minutes and 5 minutes. This could be useful for testing at different intervals at different times of day - for example, more frequently during business hours and less frequently during inactive times. It could also be used as the receiver of an alert rule webhook: if a given test triggers an alert, then increase the testing frequency to get more granular data.

First, an API call is made to get a test’s current configuration. Then the configuration is modified to change the test interval. Finally, another API call is made to update the test to use the new configuration:

import fetch from 'node-fetch';

toggleTestInterval();

async function toggleTestInterval() {
   // Define HTTP request values
   const oauth_bearer_token = "YOUR-OAUTH-BEARER-TOKEN-HERE"
   const test_id = 123456;

   // Get the current test configuration
   let resp = await fetch(`https://api.thousandeyes.com/v7/tests/web-transactions/${test_id}`, {
       headers: {'Authorization': `Bearer ${oauth_bearer_token}`}
   });
   let body = await resp.json();
   let test_config = body;

   // Toggle the interval between 600 seconds and 300 seconds
   test_config['interval'] = test_config['interval'] == 600 ? 300 : 600;

   // Delete read-only fields from the test configuration before making the call to update
   delete test_config.testId;
   delete test_config.savedEvent;

   // Call the API to update the test configuration using the new interval
   resp = await fetch(`https://api.thousandeyes.com/v7/tests/${test_config['type']}/${test_id}`, {
       headers: {
           'Authorization': `Bearer ${oauth_bearer_token}`,
           'Content-Type': 'application/json'},
       method: 'PUT',
       body: JSON.stringify(test_config)
   });
};

Next Steps

Review the ThousandEyes API v7 Reference for more details on API endpoints and request/response characteristics, such as:

  • Time spans

  • Pagination

  • Rate limiting

Watch the Short & Sweet into ThousandEyes API Suite on-demand breakout session from Cisco Live Amsterdam 2023. If you use Postman as your HTTP client, you should import the ThousandEyes Postman Collection.

Last updated