Metric POST sample

These samples generate an API request to POST metric data on a managed resource.

Leave Feedback

Curl

curl -k https://{api-url}/api/v2/metric/tenants/{tenantId}/rtypes/DEVICE/resources/{resource_id}/metrics -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept: application/json" -d '[{"metricName" : "{metric_name}","instanceName" : "{instance_name}","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();
      }
  }
}