Curl

curl -k https://{api-url}/api/v2/tenants/{tenantId}/alert -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"serviceName": "{service_name}","device":{"hostName":"{host_name}","resourceUUID":"{resource_id}","providerUUID":"{provider_id}","systemUUID":"{system_id}","macAddress":"{mac_address}","ipAddress":"{id_address}"},"subject":"{subject}", "alertTime":"{alert_time}","currentState":"{surrent_state}", "app":"{app_name}","alertType":"{alert_type}","component": "{component_name}","description":"{description}","monitorName":"{monitor_name}"}'

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();
		}
	}
}