Getting Started with APIs
Introduction
Overview
OpsRamp provides REST APIs to:
Get information about managed resources from OpsRamp.
Send information about managed resources to OpsRamp.
Configure OpsRamp to take management actions.
Authentication
OpsRamp APIs use OAuth 2.0 based authentication.
API URL
OpsRamp supports the following API URLs:
For Partner Users:
If partner is custom branded, use partner custom branded API URL – https://<partner_name>.api.opsramp.com. For example, if partner name is Alpha, provide https://alpha.api.opsramp.com as the API URL.
If partner is NOT custom branded, use https://api.opsramp.com as the API URL.
For Client Users:
If client and partner are custom branded, use client custom branded API URL – https://<client_name>.api.opsramp.com. For example, if client name is Logix, provide https://logix.api.opsramp.com as the API URL.
If client is custom branded, but partner is NOT custom branded, use https://api.opsramp.com as the API URL.
Each API request has the following header format:
Header
Value
Accept
application/json
Content-Type
application/json
Authorization
Bearer {accessToken} or Basic base64_encode(loginName:password)
API Request Throttling
API throttling limits the number of requests an API server accepts within a time period. The API server rejects requests that exceed the limit and will return 429 Too Many Requests status code.
OpsRamp throttles API requests to ensure a better quality of service. The following limits apply for each tenant (service provider, partner, and client). API requests made after a throttling limit will fail with a 429 status code error.
Throttling Limits
API Category
GET (non-paginated) (requests/minute)
GET (paginated) (requests/minute)
POST/DELETE/PUT (requests/minute)
Note: The API rate limits may change to ensure better performance and service, hence it is advisable to use HTTP headers while making API requests.
Response headers include usage against limits
API response headers include information on usage against throttling limits so that application making API request can self-regulate their requests.
HTTP Header
Description
Example
X-RateLimit-Limit
Number of requests the user is allowed to make per minute.
X-RateLimit-Limit: 500
X-RateLimit-Remaining
Number of requests remaining in the current rate limit window.
X-RateLimit-Remaining: 14
X-RateLimit-Reset
The time at which the current rate limit window resets. Time in UTC epoch seconds.
X-RateLimit-Reset: 1491397260
Sample Error Response
Below is the sample response generated if the API requests exceed the rate limit.
{
"error" : "throttled",
"error_description" : "Too Many Requests"
}
Return Status Codes
Each API call returns one of the following return codes.
Status
Message
Details
200
Success
The request has succeeded.
400
Bad Request
Unable to authenticate.
401
Unauthorized
The system/user is not authorized to use the API.
404
Not found
The requested resource was not found.
405
Method not allowed
The HTTP action is not allowed for the requested REST API, or it is not supported by any API.
407
Proxy Authentication Required
Token is expired.
410
Gone
Tenant is unavailable or deactivated.
429
Too Many Requests
API rate limit is reached and request made after the rate limit fails.
500
Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request.
Generate API Requests
Prior to initiating an API request install the integration, obtain the access token and then generate the API request.
Step 1: Install Integration
This integration is the channel through which the API communicates with OpsRamp.
Each integration has an OAuth Key and Secret, which is used to obtain an OAuth Access Token.
Step 2: Generate an Access Token
Prior to making API requests, obtain an access token using the OAuth Key and Secret.
Steps to obtain OAuth Key and Secret.
Click Setup.
Click Integrations on the left-hand side panel and then click Integrations. Integrations page appears.
Click Available Integrations and then click on the required integration.
Click Install to install the integration.
Select authentication type OAUTH2 and then click Save.
Capture the Key and Secret for the integration.
Authenticate with OpsRamp using auth API as below
Curl
curl -k https://<api-url>/auth/oauth/token -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: application/json" -d "grant_type=client_credentials&client_id=QSVGpk9u9YB6u7NhXCavBeFJhY68dcDt&client_secret=TSXd9h35ZDEWGs6YAgf9338MjTJ8cX97VkaKk2aanzaKrz5V9wC8xBk63EqECmV7" -X POST
Python
import os, sys, json, time, base64 import urllib2 is_urllib_request = False try: # For Python 3.0 and later from urllib.request import urlopen, install_opener, build_opener, Request, HTTPBasicAuthHandler from urllib.error import HTTPError, URLError from urllib.parse import urlencode is_urllib_request = True except ImportError: # Fall back to Python 2's urllib2 from urllib import urlencode from urllib2 import urlopen, install_opener, build_opener, Request, HTTPBasicAuthHandler, HTTPError, URLError config_json = { 'server' : 'api.opsramp.com', 'api_key' : 'API_KEY', 'api_secret': 'API_SECRET', 'client_id' : 'CLIENT_ID' } TIMEOUT = 120 config = None class OpsRampConfiguration: def __init__(self, config_json): self.server = config_json['server'] self.api_key = config_json['api_key'] self.api_secret = config_json['api_secret'] self.client_id = config_json['client_id'] def init_config(config_json): global config config = OpsRampConfiguration(config_json) ''' Generic HTTP GET/POST method ''' def httpPost(url, headers={}, data=None, user=None, passwd=None): try: http_headers = { 'Content-Type' : 'application/json', 'Accept' : '*/*' } http_headers.update(headers) req = Request(url, data, http_headers) if user and passwd: authhandler = HTTPBasicAuthHandler() authhandler.add_password(None, url, user, passwd) install_opener(build_opener(authhandler)) return urlopen(req, timeout=TIMEOUT).read() except HTTPError as emsg: if emsg.getcode() == 500: return emsg.read() else: print emsg.read() raise Exception(emsg) except URLError as emsg: raise Exception(emsg.reason) except: raise ''' Get opsramp access token using api key/secret for further communication ''' def get_access_token(): url = "https://%s/auth/oauth/token" % (config.server) print url print config.api_key print config.api_secret print config.client_id data = urlencode({ "client_id" : config.api_key, "client_secret" : config.api_secret, "grant_type" : "client_credentials" }) if is_urllib_request: data = data.encode() headers = {"Content-Type": "application/x-www-form-urlencoded", "Accept" : "application/json"} try: result = json.loads(httpPost(url, headers, data)) config.access_token = result['access_token'] except Exception as emsg: raise Exception("Error while getting access token - " + str(emsg)) if __name__ == '__main__': try: init_config(config_json) get_access_token() print config.access_token except Exception as e: print ("main function failed - " + str(e))
Java
package com.opsramp.examples.rest; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpException; import org.apache.http.HttpHeaders; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import com.google.gson.JsonElement; import com.google.gson.JsonParser; /** * Sample program to fetch access token from token end point */ public class GetAccessToken { /** * Main program which invokes get access token request * @param args * @throws IOException * @throws HttpException */ public static void main(String[] args) throws IOException, HttpException { //Replace the token end point, api key and secrets accordingly String TOKEN_ENDPOINT = "https://<api-url>/auth/oauth/token"; String API_KEY = "AFBS9BkX72PYsgQn9GvJKUquDQnRuSKD"; String API_SECRET = "6MqBTZK9DUTVREECrVQV2UEtGub2uGfvY4zq252GKTE4BWNCEXN9HJW3u3cQR8Nn"; //Performing access token request String response = invokeTokenRequest(TOKEN_ENDPOINT, API_KEY, API_SECRET); System.out.println(response); String accessToken = null; if(response != null && !response.isEmpty()) { JsonElement json = new JsonParser().parse(response); JsonElement token = json.getAsJsonObject().get("access_token"); if(token != null && !token.isJsonNull()) { accessToken = token.getAsString(); } } System.out.println("Access Token: " + accessToken); } /** * Fetches access token from given token end point * @param tokenEndPoint * @param apiKey * @param apiSecret * @return * @throws HttpException * @throws IOException */ public static String invokeTokenRequest(final String tokenEndPoint, final String apiKey, final String apiSecret) throws HttpException, IOException { CloseableHttpClient httpclient = HttpClients.custom().build(); try { List parametersBody = new ArrayList(); parametersBody.add(new BasicNameValuePair("grant_type", "client_credentials")); parametersBody.add(new BasicNameValuePair("client_id", apiKey)); parametersBody.add(new BasicNameValuePair("client_secret", apiSecret)); HttpPost httpPost = new HttpPost(tokenEndPoint); httpPost.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); httpPost.setEntity(new UrlEncodedFormEntity(parametersBody, StandardCharsets.UTF_8.toString())); System.out.println("n" + httpPost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPost); try { System.out.println("Response " + response.getStatusLine()); String responseBody = null; if(response.getEntity() != null) { responseBody = EntityUtils.toString(response.getEntity()); } return responseBody; } finally { response.close(); } } finally { httpclient.close(); } } } }
Capture OAuth authorization token from response
Note:
Validity period of the access token is 2 hours.
Repeat above instructions if the token expires.
Appendix – Generating API Requests
Example: Get inventory of managed resources within a client
Below are the sample codes to make an API request to get the inventory details of resources within a client.
Get list of Devices.
Curl
curl -k -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X GET https://<api-url>/api/v2/tenants/client_622733/devices/minimal
Search device details by name.
Curl
curl -k -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X GET https://<api-url>/api/v2/tenants/client_622733/devices/search?queryString=hostName:prod-Test-01
Search devices by UUID.
Curl
curl -k -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X GET https://<api-url>/api/v2/tenants/client_622733/devices/search?queryString=resourceUUID:60c6f02e-5080-46a7-856b-f1f2a1997603
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 "ntAccessToken: " + 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(); } } }
Example: Get time series metric data for a managed resource
Below are the sample codes to generate an API request to get metric data for a managed resource.
Get resource ID and resource type using Search Devices API.
Curl
curl -k -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X GET "https://<api-url>/api/v2/tenants/client_622733/devices/search?queryString=hostName:prod-Test-01"
Capture resource ID and resource type from the response.
Get metric name from the list of available metrics on a device.
Curl
curl -k -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X GET "https://<api-url>/api/v2/metric/tenants/client_622733/rtypes/DEVICE/resources/i-4cf5c094/metrics"
Capture metric from response Get the time series response for the resource ID, resource type and metric (startTime and endTime are UNIX timestamps).
Curl
curl -k -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X GET "https://<api-url>/api/v2/metric/search?tenant=client_622733&rtype=DEVICE&resource=i-4cf5c094&metric=system.cpu.utilization&startTime=1444973469&endTime=1445002269"
Sample metric and start/end times are
metric=system.cpu.utilization&startTime=1444973469&endTime=1463772116049
Note:
Start/end dates from the curl from Linux
date +%s #Current time
date -d “1 hour ago” +%s #1 Hour ago
date -d “1 day ago” +%s #1 Day ago
date -d “1 month ago” +%s #1 Month ago
Start/end dates from the curl from OS X
date +%s #Current time
date -v-1H +%s #1 Hour ago
date -v-1d +%s #1 Day ago
date -v-1m +%s #1 Month ago
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 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 = 'vistara.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(); } } }
Example: Post a metric against a resource
Below are the sample codes to generate an API request to post a metric on a resource.
Curl
curl -k https://<api-url>/api/v2/metric/tenants/client_622733/rtypes/DEVICE/resources/i-4cf5c094/metrics -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept: application/json" -d '[{"metricName" : "system.cpu.utilization","instanceName" : "system.cpu.utilization","instanceVal" : "13.50","ts" : "1448274610"}]' -X POST
Python
import urllib import urllib2 import json, sys import time API_SERVER = "API_SERVER" 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={}, 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)) ''' Post metrics ''' def post_metrics(rsrc_id, metric_data): try: headers = { "Authorization" : "Bearer " + config.access_token, "Content-Type" : "application/json", "Accept" : "application/json" } post_metrics_url = "https://%s/api/v2/metric/tenants/%s/rtypes/DEVICE/resources/%s/metrics" % (API_SERVER, CLIENT_ID, rsrc_id) data = str(json.dumps(metric_data)) httpRequest(post_metrics_url, data, headers, 'POST') 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, '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_ID = "702c19c4-1991-4e99-8c5f-4104c061fe25" metric_data = [{ "metricName" : "system.ping.rta", "instanceVal" : "16.50", "instanceName" : "rta", "ts" : "1467983770" }] post_metrics(RESOURCE_ID, metric_data) except Exception as e: print ("Failed: {0}".format(e)) sys.exit(0)
Java
package com.opsramp.examples.rest; import java.io.IOException; 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.HttpPost; import org.apache.http.entity.ByteArrayEntity; 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 post metric against a resource */ public class PostMetric { /** * Main program which posts a metric against a resource * @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"; //Posting a metric String ENDPOINT = "https://<api-url>/api/v2/metric/tenants/client_99999" + "/rtypes/DEVICE/resources/702c19c4-1991-4e99-8c5f-4104c061fe25/metrics"; String PAYLOAD = "[{"metricName" : "system.ping.rta","instanceName": "rta"," + ""instanceVal" : "16.50","ts" : "1467983770"}]"; String response = invokePostRequest(ACCESS_TOKEN, ENDPOINT, PAYLOAD, 0); System.out.println(response); } /** * Posts data to given end point * @param accessToken * @param endPoint * @param payload * @return * @throws HttpException * @throws IOException */ public static String invokePostRequest(final String accessToken, final String endPoint, final String payload, final int currentRetryCount) throws HttpException, IOException { CloseableHttpClient httpclient = HttpClients.custom().build(); try { HttpPost httpPost = new HttpPost(endPoint); httpPost.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); httpPost.setEntity(new ByteArrayEntity(payload.getBytes(StandardCharsets.UTF_8.toString()))); System.out.println("n" + httpPost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPost); 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) {} invokePostRequest(accessToken, endPoint, payload, currentRetryCount+1); } } return responseBody; } finally { response.close(); } } finally { httpclient.close(); } } }
Example: Get open alerts
Below are the sample codes to generate an API request to get the list of open alerts.
Curl
curl -k -H “Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570” -H “Content-Type: application/json” -H “Accept:application/json” -X GET “https://<partner_name>.api.ospramp.com/api/v2/tenants/client_622733/alerts/search?queryString=actions:OPEN”
Python
import urllib import urllib2 import json, sys import time API_SERVER = "API_SERVER" 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={}, 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 open alerts information from OpsRamp ''' def get_open_alerts(ACCESS_TOKEN, query_string=""): headers = { "Authorization" : "Bearer " + ACCESS_TOKEN, "Content-Type" : "application/json" } alerts_search_url = "https://%s/api/v2/tenants/%s/alerts/search?queryString=%s" % (API_SERVER, CLIENT_ID, query_string) try: response = json.loads(httpRequest(device_search_url, None, headers)) return response except Exception, emsg: print emsg sys.exit(2) ''' 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')) return result['access_token'] except Exception as emsg: raise Exception("Error while getting access token - " + str(emsg)) if __name__ == '__main__': try: ACCESS_TOKEN = str(get_access_token()) ''' need to provide the query string based on requirement ''' query_string = "actions:OPEN" open_alerts = get_open_alerts(ACCESS_TOKEN,query_string) 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 open alerts within a client */ public class GetOpenAlerts { /** * Main program which invokes get open alerts 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 open alerts String ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/alerts/search" + "?queryString=actions:OPEN"; String 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(); } } }
Example: Post an alert against a resource
Below are the sample codes to generate an API request to post alerts on a resource.
Curl
curl -k https://<api-url>/api/v2/tenants/client_622733/alert -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"serviceName": "CPU","device":{"hostName":"Think-pad","resourceUUID":"DEV0000011767","providerUUID":"11767","systemUUID":"11767","macAddress":"2E:8B:EB:32:7A:F9","ipAddress":"172.2.229.109"},"subject":"Test API Alert for car", "alertTime":"2014-11-05 11:26:00","currentState":"CRITICAL", "app":"OPSRAMP","alertType":"Maintenance","component": "C","description":"api calls","monitorName":"test"}'
Python
import urllib import urllib2 import json, sys import time API_SERVER = "API_SERVER" 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={}, 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)) ''' Post alert using REST API ''' def post_alert(resource_name, resource_ip, mname, mvalue, poll_time, component=""): alert_payload = { "serviceName": mname, "device": { "hostName": resource_name, "ipAddress": resource_ip }, "subject": "Critical. %s=%s" % (mname, mvalue), "description": "Critical. %s=%s" % (mname, mvalue), "alertTime": time.strftime("%F %T", time.gmtime(poll_time)), "currentState": "Critical", "alertType": "Monitoring", "app": "OPSRAMP", "component": "%s-%s" % (mname, component) } headers = { "Authorization" : "Bearer " + ACCESS_TOKEN } alert_url = "https://%s/api/v2/tenants/%s/alert" % (API_SERVER, CLIENT_ID) data = str(json.dumps(alert_payload)) httpRequest(alert_url, data, headers, 'POST') ''' 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')) 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_name = "BVRMLPT057" resource_ip = "172.28.102.50" mname = "CPU" mvalue = "90" poll_time = "2014-11-05 11:26:00" post_alert(resource_name, resource_ip, mname, mvalue, poll_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.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.HttpPost; import org.apache.http.entity.ByteArrayEntity; 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 post an alert against a resource */ public class PostAlert { /** * Main program which posts an alert against a resource * @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"; //Posting an alert String ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/alert"; String PAYLOAD = "{"serviceName": "CPU","device":{"hostName":"HYDLPT220"," + ""resourceUUID":"702c19c4-1991-4e99-8c5f-4104c061fe25","systemUUID":"11767"," + ""macAddress":"2E:8B:EB:32:7A:F9","ipAddress":"172.2.229.109"},"subject":"Test API Alert"," + ""alertTime":"2014-11-05 11:26:00","currentState":"CRITICAL", "app":"OPSRAMP"," + ""alertType":"Maintenance","component": "C","description":"Test Alert from API Call"," + ""monitorName":"TEST"}"; String response = invokePostRequest(ACCESS_TOKEN, ENDPOINT, PAYLOAD, 0); System.out.println(response); } /** * Posts data to given end point * @param accessToken * @param endPoint * @param payload * @return * @throws HttpException * @throws IOException */ public static String invokePostRequest(final String accessToken, final String endPoint, final String payload, final int currentRetryCount) throws HttpException, IOException { CloseableHttpClient httpclient = HttpClients.custom().build(); try { HttpPost httpPost = new HttpPost(endPoint); httpPost.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); httpPost.setEntity(new ByteArrayEntity(payload.getBytes(StandardCharsets.UTF_8.toString()))); System.out.println("n" + httpPost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPost); 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) {} invokePostRequest(accessToken, endPoint, payload, currentRetryCount+1); } } return responseBody; } finally { response.close(); } } finally { httpclient.close(); } } }
Example: Assign schedule maintenance to a device
Below are the sample codes to generate an API request to manage the schedule maintenance window.
Create a schedule maintenance window.
Curl
curl -k -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X POST https://<api-url>/api/v2/tenants/client_622733/scheduleMaintenances -d
{ "name": "Schedule-Maintenances-Name", "description": "Schedule-Maintenances-DESC", "dontRunRBA": "false", "dontInstallPatch": "false", "devices": [{ "hostName": "prod-Test-01" }], "schedule": { "type": "One-Time", "startTime": "2016-07-01T08:21:00+0000", "endTime": "2016-07-01T08:45:00+0000", "timezone": "America/Los_Angeles" } }
Search for a scheduled maintenance window by name.
Curl
curl -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X GET https://<api-url>/api/v2/tenants/client_603003/scheduleMaintenances/search?queryString=name:ondemand
Suspend a scheduled maintenance window.
Curl
curl -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X POST https://<api-url>/api/v2/tenants/client_603003/scheduleMaintenances/346248/suspend
Resume a scheduled maintenance window.
Curl
curl -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X POST https://<api-url>/api/v2/tenants/client_603003/scheduleMaintenances/346248/resume
Delete a scheduled maintenance window.
Curl
curl -H "Authorization: Bearer be1eb787-9994-4de8-b060-4d1b201eb570" -H "Content-Type: application/json" -H "Accept:application/json" -X DELETE https://<api-url>/api/v2/tenants/client_603003/scheduleMaintenances/346248
Below are the sample codes of Python and Java to manage a schedule maintenance window.
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 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)) def schedule_maintenance_actions(URL, DATA): headers = { "Authorization" : "Bearer " + ACCESS_TOKEN, "Content-Type" : "application/json" } try: response = json.loads(httpRequest(URL, DATA, headers, 0, 'GET')) except Exception, emsg: print emsg sys.exit(2) ''' 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: ACCESS_TOKEN = str(get_access_token()) ''' Creating a schedule maintenance window ''' url = "https://{0}/api/v2/tenants/{1}/scheduleMaintenances".format(API_SERVER, CLIENT_ID) data = { "name" : "Test Maintenance from API", "description" : "Test Maintenance from API", "dontRunRBA" :"false", "dontInstallPatch" :"false", "devices" : [{ "uniqueId": "702c19c4-1991-4e99-8c5f-4104c061fe25" }], "schedule" : { "type":"One-Time", "startTime": "2016-07-07T08:21:00+0000", "endTime": "2016-07-09T08:45:00+0000", "timezone":"America/Los_Angeles" } } ''' Searching a schedule maintenance window by name ''' url = """https://%s/api/v2/tenants/%s/scheduleMaintenances/search?queryString=""" + urllib.encode("name:Test Maintenance from API") %(API_SERVER, CLIENT_ID) data = None ''' Suspending a schedule maintenance window ''' url = "https://{0}/api/v2/tenants/{1}/scheduleMaintenances/123456/suspend".format(API_SERVER, CLIENT_ID) data = {"pattern" : "now"} ''' Resuming a schedule maintenance window ''' url = "https://{0}/api/v2/tenants/{1}/scheduleMaintenances/123456/resume".format(API_SERVER, CLIENT_ID) data = None ''' Deleting a schedule maintenance window ''' url = "https://{0/api/v2/tenants/{1}/scheduleMaintenances/123456".format(API_SERVER, CLIENT_ID) data = None schedule_maintenance_actions(url, data) except Exception as e: print ("Failed - " + str(e))
Java
package com.opsramp.examples.rest; import java.io.IOException; import java.net.URI; 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.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ByteArrayEntity; 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 perform schedule maintenance actions */ public class ScheduleMaintenanceActions { /** * Main program which performs schedule maintenance actions * @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"; //Creating a schedule maintenance window String ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/scheduleMaintenances"; String PAYLOAD = "{"name":"Test Maintenance from API","description":"Test Maintenance from API"," + ""dontRunRBA":"false","dontInstallPatch":"false", "devices":[{"uniqueId":" + ""702c19c4-1991-4e99-8c5f-4104c061fe25"}],"schedule":{"type":"One-Time","startTime":" + ""2016-07-07T08:21:00+0000","endTime":"2016-07-09T08:45:00+0000","timezone":" + ""America/Los_Angeles"}}"; String response = invokePostRequest(ACCESS_TOKEN, ENDPOINT, PAYLOAD); System.out.println(response); //Searching a schedule maintenance window by name ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/scheduleMaintenances/search" + "?queryString=" + URLEncoder.encode("name:Test Maintenance from API", StandardCharsets.UTF_8.toString()); response = invokeGetRequest(ACCESS_TOKEN, ENDPOINT); System.out.println(response); //Suspending a schedule maintenance window ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/scheduleMaintenances/123456/suspend"; PAYLOAD = "{"pattern": "now"}"; response = invokePostRequest(ACCESS_TOKEN, ENDPOINT, PAYLOAD); System.out.println(response); //Resuming a schedule maintenance window ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/scheduleMaintenances/123456/resume"; response = invokePostRequest(ACCESS_TOKEN, ENDPOINT, null); System.out.println(response); //Deleting a schedule maintenance window ENDPOINT = "https://<api-url>/api/v2/tenants/client_99999/scheduleMaintenances/123456"; response = invokeDeleteRequest(ACCESS_TOKEN, ENDPOINT); 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) throws HttpException, IOException { return invokeRequest(accessToken, endPoint, null, new HttpGet(), 0); } /** * Deletes data at given end point * @param accessToken * @param endPoint * @return * @throws HttpException * @throws IOException */ public static String invokeDeleteRequest(final String accessToken, final String endPoint) throws HttpException, IOException { return invokeRequest(accessToken, endPoint, null, new HttpDelete(), 0); } /** * Posts data to given end point * @param accessToken * @param endPoint * @param payload * @return * @throws HttpException * @throws IOException */ public static String invokePostRequest(final String accessToken, final String endPoint, final String payload) throws HttpException, IOException { return invokeRequest(accessToken, endPoint, payload, new HttpPost(), 0); } /** * Invokes an OAuth2 API request * @param accessToken * @param endPoint * @param payload * @param httpRequest * @return * @throws HttpException * @throws IOException */ public static String invokeRequest(final String accessToken, final String endPoint, final String payload, HttpRequestBase httpRequest, final int currentRetryCount) throws HttpException, IOException { CloseableHttpClient httpclient = HttpClients.custom().build(); try { httpRequest.setURI(URI.create(endPoint)); httpRequest.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()); httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); httpRequest.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); if(httpRequest instanceof HttpEntityEnclosingRequestBase && payload != null) { ((HttpEntityEnclosingRequestBase) httpRequest) .setEntity(new ByteArrayEntity(payload.getBytes(StandardCharsets.UTF_8.toString()))); } System.out.println("n" + httpRequest.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpRequest); 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) {} invokeRequest(accessToken, endPoint, payload, httpRequest, currentRetryCount+1); } } return responseBody; } finally { response.close(); } } finally { httpclient.close(); } } }
Last updated
Was this helpful?