Documentation is now available for the Fall 2020 Update release!

Inventory GET sample

These samples retrieve inventory of managed resources within a client.

Leave Feedback

Curl

Get list of devices

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/minimal

Search device details by name

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}

Search devices by UUID

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=resourceUUID:{resource_UUID}

Python

import urllib
import urllib2
import json, sys
import time

API_SERVER = "api.opsramp.com"
CLIENT_ID  = "CLIENT_ID"
API_KEY    = "API_KEY"
API_SECRET = "API_SECRET"


''' Python HTTP client to make GET/POST requests '''
def httpRequest(url, data=None, headers={}, 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() == 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 resource/device information from OpsRamp '''
def get_resources(ACCESS_TOKEN, query_string="", pageSize=500, pageNo=None):
    headers = {
        "Authorization" : "Bearer " + ACCESS_TOKEN,
        "Content-Type"  : "application/json"
    }
    device_search_url = "https://%s/api/v2/tenants/%s/devices/search?pageSize=%s&queryString=%s"
                          % (API_SERVER, CLIENT_ID, pageSize, query_string)
    if pageNo:
        device_search_url += "&pageNo=" + str(pageNo)
    try:
        response = json.loads(httpRequest(device_search_url, None, headers))
        print "\t" + device_search_url
        ''' Capture full devices information using response'''
        ''' print "\t" + json.dumps(response)'''
        return response
    except Exception, emsg:
        print emsg
        print 'Resource does not exist in OPSRAMP, Please create new Resource'
        sys.exit(2)


def get_devices_data(ACCESS_TOKEN, pageSize=500, query_string=""):
    devices = {}

    def get_device_data(rsrcInfo):
        for resource in rsrcInfo['results']:
            devices[resource['id']] = resource['generalInfo']['hostName']

        if rsrcInfo['nextPage']:
            rsrcs = get_resources(ACCESS_TOKEN, query_string, pageSize, rsrcInfo['pageNo'] + 1)
            get_device_data(rsrcs)

    resources = get_resources(ACCESS_TOKEN, query_string, pageSize)
    get_device_data(resources)
    return devices


''' 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, 'POST'))
        print "\n\tAccessToken: " + result['access_token'] + "\n";
        return result['access_token']
    except Exception as emsg:
        raise Exception("Error while getting access token - " + str(emsg))


''' Execution starts here'''
if __name__ == '__main__':
    try:

        ACCESS_TOKEN = str(get_access_token())

        pageSize=500
        query_string = ""

        devices = get_devices_data(ACCESS_TOKEN, pageSize, query_string)

        ''' All Device ids & names will be available in devices dictionary'''
        print json.dumps(devices)
    except Exception as e:
        print ("Failed: {0}".format(e))

    sys.exit(0)

Java

package com.opsramp.examples.rest;

import java.io.IOException;
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;

/**
 * Sample program to fetch devices within a client
 */
public class GetDevices {

	/**
	 * Main program which invokes get devices 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";

		//Fetching devices minimal list
		String ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/devices/minimal";
		String response = invokeGetRequest(ACCESS_TOKEN, ENDPOINT, 0);
		System.out.println(response);

		//Performing device search using host name
		ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/devices/search"
						+ "?queryString=hostName:HYDLPT323";
		response = invokeGetRequest(ACCESS_TOKEN, ENDPOINT, 0);
		System.out.println(response);

		//Performing device search using unique id
		ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/devices/search"
						+ "?queryString=resourceUUID:5486c82c-d5fc-4e40-b238-a4f00cb387da";
		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();
		}
	}
}