Curl

The following sample code gets resource ID and resource type using the Search Devices API. The resource ID and resource type are captured from the response.

curl -k -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept:application/json" -X GET "https://{api-url}/api/v2/tenants/{tenantId}/devices/search?queryString=hostName:{host_name}"

The following sample code gets metric name from the list of available metrics on a device.

curl -k -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept:application/json" -X GET "https://{api-url}/api/v2/metric/tenants/{tenantId}/rtypes/DEVICE/resources/{resource_id}/metrics"

The following sample code gets the time series response for the resource ID, resource type and metric (startTime and endTime are UNIX timestamps).

curl -k -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept:application/json" -X GET "https://{api-url}/api/v2/metric/search?tenant={client_id}&rtype=DEVICE&resource={resource_id}&metric={metric_name}&startTime={start_time}&endTime={end_time}"

Python

import urllib
import urllib2
import json, sys
import time

API_SERVER = "api.app.vistanet.jp"
CLIENT_ID  = "CLIENT_ID"
API_KEY    = "API_KEY"
API_SECRET = "API_SECRET"

# Python HTTP client to generate GET/POST requests
def httpRequest(url, data=None, headers={}, repeat_count=None, method='GET',user=None, passwd=None):
    try:
        http_headers = {
            'Content-Type' : 'application/x-www-form-urlencoded',
            'Accept'       : 'text/html, */*',
        }
        http_headers.update(headers)
        req = urllib2.Request(url, data, http_headers)
        req.get_method = lambda: method
        if user and passwd:
            passReq = urllib2.HTTPPasswordMgrWithDefaultRealm()
            passReq.add_password(None, url, user, passwd)
            authhandler = urllib2.HTTPBasicAuthHandler(passReq)
            opener = urllib2.build_opener(authhandler)
            urllib2.install_opener(opener)

        request = urllib2.urlopen(req)
        return request.read()
    except urllib2.HTTPError, emsg:
        _msg = emsg.read()
        print emsg.getcode()
        if emsg.getcode() == 429:
            time.sleep(60)
            if repeat_count != None and repeat_count < 3:
                httpRequest(url, data, headers, repeat_count+1, method)
            print _msg
            return _msg
        elif emsg.getcode() == 500:
            print _msg
            return _msg
        else:
            print emsg.read()
            raise Exception(emsg.reason)
        raise Exception('httpRequest: HTTPError - ' + str(emsg))
    except urllib2.URLError, emsg:
        raise Exception('httpRequest: URLError - ' + str(emsg))
    except Exception, emsg:
        raise Exception('httpRequest: Exception - ' + str(emsg))

# Get metrics
def get_available_metrics(rsrc_id, rsrc_type):
    try:
        headers = {
            "Authorization" : "Bearer " + ACCESS_TOKEN,
            "Content-Type"  : "application/json",
            "Accept"        : "application/json"
        }
        available_metrics_url = "https://{0}/api/v2/metric/tenants/{1}/rtypes/{2}/resources/{3}/metrics"
        % (API_SERVER, CLIENT_ID, rsrc_type, rsrc_id)

        return httpRequest(available_metrics_url, None, headers, 0, 'GET')
    except Exception as emsg:
        print 'Failed to get metric data %s' % (emsg)

# Time Series metrics data
def get_timeseries_metrics_data(rsrc_id, rsrc_type,metric_name,start_time,end_time):
    try:
        headers = {
            "Authorization" : "Bearer " + ACCESS_TOKEN,
            "Content-Type"  : "application/json",
            "Accept"        : "application/json"
        }

        timeseries_metrics_url = "https://{0}/api/v2/metric/search?tenant={1}&rtype={2}&resource={3}&metric={4}&startTime={5}&endTime={6}"
         % (API_SERVER, CLIENT_ID, rsrc_type, rsrc_id, metric_name,start_time,end_time)

        return httpRequest(timeseries_metrics_url, None, headers, 0, 'GET')
    except Exception as emsg:
        print 'Failed to post metric data %s' % (emsg)

# Get OpsRamp access token using api key/secret for further communication
def get_access_token():
    url = "https://%s/auth/oauth/token" % (API_SERVER)

    data = urllib.urlencode({
        "client_id"     : API_KEY,
        "client_secret" : API_SECRET,
        "grant_type"    : "client_credentials"
    })

    headers = {"Content-Type": "application/x-www-form-urlencoded", "Accept" : "application/json"}
    try:
        result = json.loads(httpRequest(url, data, headers, None, 'POST'))
        return result['access_token']
    except Exception as emsg:
        raise Exception("Error while getting access token - " + str(emsg))

if __name__ == '__main__':
    try:
        global ACCESS_TOKEN
        ACCESS_TOKEN = str(get_access_token())

        RESOURCE_TYPE = "DEVICE"
        RESOURCE_ID = "702c19c4-1991-4e99-8c5f-4104c061fe25"

        available_metrics = get_available_metrics(RESOURCE_ID, RESOURCE_TYPE)

        ''' Fetching time series metric data for the resource '''

        METRIC_NAME = 'opsramp.agent.status'

        ''' start time and end time in epoch time '''
        start_time = "1444973469"
        end_time = "1467980181"
        timeseries_data = get_timeseries_metrics_data(RESOURCE_ID, RESOURCE_TYPE, METRIC_NAME,start_time,end_time)

    except Exception as e:
        print ("Failed: {0}".format(e))

    sys.exit(0)

Java

package com.opsramp.examples.rest;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

/**
 * Sample program to get time series metric data of a resource
 */
public class GetTimeSeriesMetricData {

	/**
	 * Main program which invokes time series metric data request
	 * @param args
	 * @throws HttpException
	 * @throws IOException
	 */
	public static void main(String[] args) throws HttpException, IOException {
		//Replace the end point and access token accordingly
		String ACCESS_TOKEN = "a0f46d75-534d-4180-b4ec-65a23eb1ae39";

		//Performing device search using host name
		String ENDPOINT = "https://{api-url}/api/v2/tenants/client_99999/devices/search"
					+ "?queryString=" + URLEncoder.encode("hostName:HYDLPT220", StandardCharsets.UTF_8.toString());
		URLEncoder.encode(ENDPOINT, StandardCharsets.UTF_8.toString());
		String response = invokeGetRequest(ACCESS_TOKEN, ENDPOINT, 0);
		if(response == null || response.isEmpty()) {
			return;
		}
		System.out.println(response);

		//Capturing resource id and type from response
		JsonElement json = new JsonParser().parse(response);
		JsonElement count = json.getAsJsonObject().get("totalResults");
		if(count == null || count.isJsonNull()) {
			return;
		}
		if(count.getAsInt() == 0) {
			return;
		}
		JsonElement resourceJson = json.getAsJsonObject().get("results")
										.getAsJsonArray().get(0);
		String resourceUID = null, resourceType = null;
		if(resourceJson.getAsJsonObject().get("id") != null) {
			resourceUID = resourceJson.getAsJsonObject().get("id").getAsString();
		}
		if(resourceJson.getAsJsonObject().get("type") != null) {
			resourceType = resourceJson.getAsJsonObject().get("type").getAsString();
		}
		System.out.println("Total Results: " + count.getAsInt());
		System.out.println("Resource Id: " + resourceUID);
		System.out.println("Resource Type: " + resourceType);

		if(resourceUID == null || resourceUID.isEmpty()
				|| resourceType == null || resourceType.isEmpty()) {
			return;
		}

		//Fetching available metrics list of the resource
		ENDPOINT = "https://{api-url}/api/v2/metric/tenants/client_99999"
						+ "/rtypes/" + resourceType+ "/resources/" + resourceUID+ "/metrics";
		response = invokeGetRequest(ACCESS_TOKEN, ENDPOINT, 0);
		if(response == null || response.isEmpty()) {
			return;
		}
		System.out.println(response);

		//Capturing metric name from response
		json = new JsonParser().parse(response);
		if(!json.isJsonArray() || json.getAsJsonArray().size() == 0) {
			return;
		}

		JsonElement metricJson = json.getAsJsonArray().get(0);

		String metricName = null;
		if(metricJson.getAsJsonObject().get("metricName") != null) {
			metricName = metricJson.getAsJsonObject().get("metricName").getAsString();
		}
		if(metricName == null || metricName.isEmpty()) {
			return;
		}
		System.out.println("Metric Name: " + metricName);

		//Fetching time series metric data for the resource
		ENDPOINT = "https://{api-url}/api/v2/metric/search?tenant=client_99999"
						+ "&rtype=" + resourceType + "&resource=" + resourceUID +
						"&metric=" + metricName + "&startTime=1444973469&endTime=1467980181";
		response = invokeGetRequest(ACCESS_TOKEN, ENDPOINT, 0);
		System.out.println(response);
	}

	/**
	 * Fetches data from given end point
	 * @param accessToken
	 * @param endPoint
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	public static String invokeGetRequest(final String accessToken, final String endPoint, final int currentRetryCount)
			throws HttpException, IOException {
		CloseableHttpClient httpclient = HttpClients.custom().build();
		try {
			HttpGet httpget = new HttpGet(endPoint);
			httpget.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString());
			httpget.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
			httpget.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);

			System.out.println("\n" + httpget.getRequestLine());
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				System.out.println("Response " + response.getStatusLine());
				String responseBody = null;
				if(response.getEntity() != null) {
					responseBody = EntityUtils.toString(response.getEntity());
					if(response.getStatusLine().getStatusCode() == 429) {
						if(currentRetryCount > 3) {
							System.out.println("Retry Max-Limit(3) reached; Dropping API: " + endPoint);
						}
						long resetTimeInSeconds = Long.valueOf(response.getFirstHeader("X-RateLimit-Reset").getValue());
						long retryInSec = resetTimeInSeconds - (new Date().getTime()/1000);
						System.out.println("\tNext retry in: " + retryInSec + "s" + " | " + endPoint);
						try {
							Thread.sleep(retryInSec*1000);
						} catch(Exception ex) {}
						invokeGetRequest(accessToken, endPoint, currentRetryCount+1);
					}
				}
				return responseBody;
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
	}
}