Alert GET sample
These samples generate an API request to get a list of open alerts.
Curl
curl -k -H "Authorization: Bearer {bearer_token}"
-H "Content-Type: application/json"
-H "Accept:application/json"
-X GET "https://{partner_name}.api.vistanet.jp/api/v2/tenants/{tenantId}/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();
}
}
}