REST API Developer's Guide

REST API v1 Examples

Example 1 - Python 2.7 POST

The following script illustrates LMv1 Authentication for a POST request in Python (version 2.7).  Specifically, the following request adds a service to the account apiAccount.logicmonitor.com:

#!/bin/env python

import requests
import json
import hashlib
import base64
import time
import hmac

#Account Info
AccessId ='J62te62B8u7WnCR846h6'
AccessKey ='{[G^PX=^Fg^32y9-x(-2Bg32vZ~^u-k4)8!9[0U^'
Company = 'apiAccount'

#Request Info: Add a service
httpVerb ='POST'
resourcePath = '/service/services'
data = '{"type":"ping","name":"LMCertification","disableAlerting":false,"pollingInterval":5,"host":"www.logicmonitor.docebosaas.com"}'

#Construct URL 
url = 'https://'+ Company +'.logicmonitor.com/santaba/rest' + resourcePath

#Get current time in milliseconds
epoch = str(int(time.time() * 1000))

#Concatenate Request details
requestVars = httpVerb + epoch + data + resourcePath

#Construct signature
signature = base64.b64encode(hmac.new(AccessKey,msg=requestVars,digestmod=hashlib.sha256).hexdigest())

#Construct headers
auth = 'LMv1 ' + AccessId + ':' + signature + ':' + epoch
headers = {'Content-Type':'application/json','Authorization':auth}

#Make request
response = requests.post(url, data=data, headers=headers)

#Print status and body of response
print 'Response Status:',response.status_code
print 'Response Body:',response.content 

 

Example 2 - Python 2.7 GET

The following script illustrates LMv1 Authentication for a GET request in Python (version 2.7).  Specifically, the following request gets details for all services in apiAccount.logicmonitor.com:

#!/bin/env python

import requests
import json
import hashlib
import base64
import time
import hmac

#Account Info
AccessId ='J62te62B8u7WnCR846h6'
AccessKey ='{[G^PX=^Fg^32y9-x(-2Bg32vZ~^u-k4)8!9[0U^'
Company = 'apiAccount'

#Request Info: Get Services
httpVerb ='GET'
resourcePath = '/service/services'
queryParams = '?filter=name~QA'

#Construct URL 
url = 'https://'+ Company +'.logicmonitor.com/santaba/rest' + resourcePath + queryParams

#Get current time in milliseconds
epoch = str(int(time.time() * 1000))

#Concatenate Request details
requestVars = httpVerb + epoch + resourcePath

#Construct signature
signature = base64.b64encode(hmac.new(AccessKey,msg=requestVars,digestmod=hashlib.sha256).hexdigest())

#Construct headers
auth = 'LMv1 ' + AccessId + ':' + signature + ':' + epoch
headers = {'Content-Type':'application/json','Authorization':auth}

#Make request
response = requests.get(url, headers=headers)

#Print status and body of response
print 'Response Status:',response.status_code
print 'Response Body:',response.content

 

Example 3 - Python 3 GET

The following script illustrates LMv1 Authentication for a GET request in Python (version 3.5).  Specifically, the following request gets details for all devices in apiAccount.logicmonitor.com:

#!/bin/env python

import requests
import json
import hashlib
import base64
import time
import hmac

#Account Info
AccessId ='48v2wRzfK94y53sq5EuF'
AccessKey ='H_D9i(f5~B^U36^K6i42=^nS~e75gy382Bf6{)P+'
Company = 'api'

#Request Info
httpVerb ='GET'
resourcePath = '/device/devices'
queryParams =''
data = ''

#Construct URL 
url = 'https://'+ Company +'.logicmonitor.com/santaba/rest' + resourcePath +queryParams

#Get current time in milliseconds
epoch =str(int(time.time() * 1000))

#Concatenate Request details
requestVars = httpVerb + epoch + data + resourcePath

#Construct signature
hmac = hmac.new(AccessKey.encode(),msg=requestVars.encode(),digestmod=hashlib.sha256).hexdigest()
signature = base64.b64encode(hmac.encode())

#Construct headers
auth = 'LMv1 ' + AccessId + ':' + signature.decode() + ':' + epoch
headers = {'Content-Type':'application/json','Authorization':auth}

#Make request
response = requests.get(url, data=data, headers=headers)

#Print status and body of response
print ('Response Status:',response.status_code)
print ('Response Body:',response.content)

 

Example 4 - Groovy GET

The following script illustrates LMv1 Authentication for a GET request in Groovy.  Specifically, the following request gets details for all services in apiAccount.logicmonitor.com:

import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
	
//define credentials and url
def accessId = 'YQQ75w6Mxx9zWIeAMq5H';
def accessKey = 'f)!Z}%spR=6en+4^s2$t32r-3=NpdQ]2T{-deI)8';
def account = 'apiAccount';
def resourcePath = "/service/services"
def url = "https://" + account + ".logicmonitor.com" + "/santaba/rest" + resourcePath;

//get current time
epoch = System.currentTimeMillis();

//calculate signature
requestVars = "GET" + epoch + resourcePath;

hmac = Mac.getInstance("HmacSHA256");
secret = new SecretKeySpec(accessKey.getBytes(), "HmacSHA256");
hmac.init(secret);
hmac_signed = Hex.encodeHexString(hmac.doFinal(requestVars.getBytes()));
signature = hmac_signed.bytes.encodeBase64();

// HTTP Get
CloseableHttpClient httpclient = HttpClients.createDefault();
httpGet = new HttpGet(url);
httpGet.addHeader("Authorization" , "LMv1 " + accessId + ":" + signature + ":" + epoch);
response = httpclient.execute(httpGet);
responseBody = EntityUtils.toString(response.getEntity());
code = response.getStatusLine().getStatusCode();

// Print Response
println "Status:" + code;
println "Body:" + responseBody;

httpclient.close();

 

Example 5 - Groovy PUT

The following script illustrates LMv1 Authentication for a PUT request in Groovy.  Specifically, the following request updates a device in account apiAccount.logicmonitor.com:

import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpPut
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

//define credentials and url
def accessId = 'YQQ75w6Mxx9zWIeAMq5H';
def accessKey = 'f)!Z}%spR=6en+4^s2$t32r-3=NpdQ]2T{-deI)8';
def account = 'apiAccount';

def resourcePath = "/device/devices/4"

def url = "https://" + account + ".logicmonitor.com" + "/santaba/rest" + resourcePath

def data = '{"name":"10.14.35.210","displayName":"ProdServer","preferredCollectorId":12,"hostGroupIds":1,"description":"a server in the production environment"}'
StringEntity params = new StringEntity(data,ContentType.APPLICATION_JSON);

epoch = System.currentTimeMillis(); //get current time

requestVars = "PUT" + epoch + data + resourcePath;

// construct signature
hmac = Mac.getInstance("HmacSHA256");
secret = new SecretKeySpec(accessKey.getBytes(), "HmacSHA256");
hmac.init(secret);
hmac_signed = Hex.encodeHexString(hmac.doFinal(requestVars.getBytes()));
signature = hmac_signed.bytes.encodeBase64();

// HTTP PUT
CloseableHttpClient httpclient = HttpClients.createDefault();
http_request = new HttpPut(url);
http_request.setHeader("Authorization" , "LMv1 " + accessId + ":" + signature + ":" + epoch);
http_request.setHeader("Accept", "application/json");
http_request.setHeader("Content-type", "application/json");
http_request.setEntity(params);
response = httpclient.execute(http_request);
responseBody = EntityUtils.toString(response.getEntity());
code = response.getStatusLine().getStatusCode();

// Print Response
println "Status:" + code;
println "Response body:" + responseBody;
httpclient.close(); 

 

Example 6 - PowerShell GET

The following script illustrates LMv1 Authentication for a GET request in PowerShell.  Specifically, the following request gets details for all services in apiAccount.logicmonitor.com:


<# Use TLS 1.2 #>
[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Tls12

<# account info #> $accessId = 'YQQ75w6Mxx9zWIeAMq5H' $accessKey = 'f)!Z}%spR=6en+4^s2$t32r-3=NpdQ]2T{-deI)8' $company = 'apiAccount' <# request details #> $httpVerb = 'GET' $resourcePath = '/service/services' <# Construct URL #> $url = 'https://' + $company + '.logicmonitor.com/santaba/rest' + $resourcePath <# Get current time in milliseconds #> $epoch = [Math]::Round((New-TimeSpan -start (Get-Date -Date "1/1/1970") -end (Get-Date).ToUniversalTime()).TotalMilliseconds) <# Concatenate Request Details #> $requestVars = $httpVerb + $epoch + $resourcePath <# Construct Signature #> $hmac = New-Object System.Security.Cryptography.HMACSHA256 $hmac.Key = [Text.Encoding]::UTF8.GetBytes($accessKey) $signatureBytes = $hmac.ComputeHash([Text.Encoding]::UTF8.GetBytes($requestVars)) $signatureHex = [System.BitConverter]::ToString($signatureBytes) -replace '-' $signature = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($signatureHex.ToLower())) <# Construct Headers #> $auth = 'LMv1 ' + $accessId + ':' + $signature + ':' + $epoch $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("Authorization",$auth) $headers.Add("Content-Type",'application/json') <# Make Request #> $response = Invoke-RestMethod -Uri $url -Method Get -Header $headers <# Print status and body of response #> $status = $response.status $body = $response.data| ConvertTo-Json -Depth 5 Write-Host "Status:$status" Write-Host "Response:$body"

 

Example 7 - PowerShell POST

The following script illustrates LMv1 Authentication for a POST request in PowerShell.  Specifically, the following request adds a service in apiAccount.logicmonitor.com:

<# Use TLS 1.2 #>
[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Tls12

<# account info #> $accessId = 'YQQ75w6Mxx9zWIeAMq5H' $accessKey = 'f)!Z}%spR=6en+4^s2$t32r-3=NpdQ]2T{-deI)8' $company = 'apiAccount' <# request details #> $httpVerb = 'POST' $resourcePath = '/service/services' $data = '{"type":"ping","name":"LMCertification","disableAlerting":false,"pollingInterval":5,"host":"www.logicmonitor.docebosaas.com"}' <# Construct URL #> $url = 'https://' + $company + '.logicmonitor.com/santaba/rest' + $resourcePath <# Get current time in milliseconds #> $epoch = [Math]::Round((New-TimeSpan -start (Get-Date -Date "1/1/1970") -end (Get-Date).ToUniversalTime()).TotalMilliseconds) <# Concatenate Request Details #> $requestVars = $httpVerb + $epoch + $data + $resourcePath <# Construct Signature #> $hmac = New-Object System.Security.Cryptography.HMACSHA256 $hmac.Key = [Text.Encoding]::UTF8.GetBytes($accessKey) $signatureBytes = $hmac.ComputeHash([Text.Encoding]::UTF8.GetBytes($requestVars)) $signatureHex = [System.BitConverter]::ToString($signatureBytes) -replace '-' $signature = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($signatureHex.ToLower())) <# Construct Headers #> $auth = 'LMv1 ' + $accessId + ':' + $signature + ':' + $epoch $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("Authorization",$auth) $headers.Add("Content-Type",'application/json') <# Make Request #> $response = Invoke-RestMethod -Uri $url -Method $httpVerb -Body $data -Header $headers <# Print status and body of response #> $status = $response.status $body = $response.data| ConvertTo-Json -Depth 5 Write-Host "Status:$status" Write-Host "Response:$body"

 

Example 8 - Ruby GET

The following script illustrates LMv1 Authentication for a GET request in Ruby.  Specifically, the following request gets details for all services in api.logicmonitor.com:

require 'net/http'
require 'net/https'
require 'uri'
require 'openssl'
require 'base64'
require 'json'
require 'date'

# Account Information
@account = 'api'
@access_id = '48v2wRzfK94y53sq5EuF'
@access_key = 'H_D9I(f5~B^U36^K6i42=^nS~e75gy382Bf6{)P+'
@http_method = 'GET'
@data = ''
@resource_path = '/service/services'

# HMAC-SHA256 + Base64 Encode
def generate_token
  timestamp = DateTime.now.strftime('%Q')
  signature = Base64.strict_encode64(
    OpenSSL::HMAC.hexdigest(
      OpenSSL::Digest.new('sha256'), 
      @access_key,
      "#{@http_method}#{timestamp}#{@data}#{@resource_path}"
    )
  )
  "LMv1 #{@access_id}:#{signature}:#{timestamp}"
end

# Build and Execute HTTP Request
uri = URI.parse("https://#{@account}.logicmonitor.com/santaba/rest#{@resource_path}")
request = Net::HTTP::Get.new uri.request_uri
request['Authorization'] = generate_token
request['Content-Type'] = 'application/json'
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start
resp = http.request(request)
code = resp.code
begin
  body = JSON.parse(resp.body)
rescue JSON::ParserError => e
  body = resp.body
end

# Print HTTP Response Code and Body
puts "Response Status: %d" % code
puts "Response Body: %s" % body


 

Example 9 - Ruby POST

The following script illustrates LMv1 Authentication for a POST request in Ruby.  Specifically, the following request adds a service in api.logicmonitor.com:

require 'net/http'
require 'net/https'
require 'uri'
require 'openssl'
require 'base64'
require 'json'
require 'date'

# Account Information
@account = 'api'
@access_id = '48v2wRzfK94y53sq5EuF'
@access_key = 'H_D9i(f5~B^U36^K6i42=^nS~e75gy382Bf6{)P+'
@http_method = 'POST'
@data = '{"type":"ping","name":"LMCertification","disableAlerting":false,"pollingInterval":5,"host":"www.logicmonitor.docebosaas.com"}'
@resource_path = '/service/services'

# HMAC-SHA256 + Base64 Encode
def generate_token
  timestamp = DateTime.now.strftime('%Q')
  signature = Base64.strict_encode64(
    OpenSSL::HMAC.hexdigest(
      OpenSSL::Digest.new('sha256'), 
      @access_key,
      "#{@http_method}#{timestamp}#{@data}#{@resource_path}"
    )
  )
  "LMv1 #{@access_id}:#{signature}:#{timestamp}"
end

# Build and Execute HTTP Request
uri = URI.parse("https://#{@account}.logicmonitor.com/santaba/rest#{@resource_path}")
request = Net::HTTP::Post.new uri.request_uri
request.body = @data
request['Authorization'] = generate_token
request['Content-Type'] = 'application/json'
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start
resp = http.request(request)
code = resp.code
begin
  body = JSON.parse(resp.body)
rescue JSON::ParserError => e
  body = resp.body
end

# Print HTTP Response Code and Body
puts "Response Status: %d" % code
puts "Response Body: %s" % body

 

Example 10 - PHP POST

The following script adds an alert rule to account api.logicmonitor.com:

<?php
$accessID = '566tp67HrUkcV0Pl09T4';
$accessKEY = 'oK)u8cYs87D~^_klRoP~63U-p1G_mn2bv6J9-1+)';
$resourcePath = "/setting/alert/rules";
$url = "https://api.logicmonitor.com/santaba/rest$resourcePath";
$epoch = round(microtime(true) * 1000);
$httpVerb = "POST";
 
$data = array
(
	"name" => "test alert rule",
	"priority" => 100,
	"datasource" => "*",
	"instance" => "*",
	"datapoint" => "*",
	"escalationInterval" => 15,
	"escalatingChainId" => 1
);

$data_string = json_encode($data, true);
$requestVars = $httpVerb . $epoch . $data_string . $resourcePath;
print "REQUESTVARS: $requestVars\n\n";
 
//Generate Signature
$sig = base64_encode(hash_hmac('sha256', $requestVars, $accessKEY));
print "SIGNATURE: $sig\n\n";
 
//Setup headers
$auth = 'LMv1 '.$accessID.':'.$sig.':'.$epoch;
print "AUTH: $auth\n\n";
 
$headers = array('Content-Type: application/json',
 'Authorization: '.$auth
);
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 
$result = curl_exec($ch);
curl_close ($ch);
 
print_r($result);
 
?>

 

Example 11 - Node.js GET

The following script gets the name and id of all devices with "prod" in the name from account api.logicmonitor.com:

// Account Info
var accessId = '48v2wRzfK94y53sq5EuF';
var accessKey = 'H_D9i(f5~B^U36^K6i42=^nS~e75gy382ki8{)P+';
var company = 'api'

// Request Details
var httpVerb = "GET";
var epoch = (new Date).getTime();
var resourcePath = "/device/devices";

// Construct signature 
var requestVars = httpVerb + epoch + resourcePath;
var crypto = require("crypto");
var hex = crypto.createHmac("sha256", accessKey).update(requestVars).digest("hex");
var signature = new Buffer(hex).toString('base64');
  
// Construct auth header
var auth = "LMv1 " + accessId + ":" + signature + ":" + epoch;
// Configure request options 
var request = require('request');
var options = 
    {
      "method" : httpVerb,
			"uri" : "https://" + company + ".logicmonitor.com/santaba/rest" + resourcePath,
			"headers": {
			    'ContentType' : 'application/json',
			    'Authorization': auth
			  },
			"qs": {
				   'fields': 'id,name',
				   'filter': 'name~ip'
				  }	
    };

// Make request
request(options, function (error, response, body) {
		if (!error && response.statusCode == 200) {
		   // Print out the response body
		   console.log(body)
		 }
	 }); 

 

What if I want to make a cURL request?

Because LMv1 API Token Authentication is a bit more complicated than Basic Auth, it is more difficult to use in a cURL command or other one line request.  If you'd like to make a one line request, consider using a script like the below that allows you to do so.

This particular example script should be used like this:

python scriptName.py --id  --key  --method  --url  --data [Request Payload]

where < > denotes a required parameter and [ ] denotes an optional parameter

 

#!/bin/env python

import requests
import json
import hashlib
import base64
import time
import hmac
import sys, getopt
from urlparse import parse_qs, urlparse

#Start with empty Account Details and populate based on arguments provided
AccessId = ''
AccessKey = ''
httpVerb = ''
url = ''
data = ''

try:
      opts, args = getopt.getopt(sys.argv[1:],"",["id=","key=","method=", "url=","data"])
except getopt.GetoptError:
      print 'Usage: python curl.py --id [Token Access Id] --key [Token Access Key] --method [HTTP Method] --url [Request URL] --data [Request Payload]'
      sys.exit(2)
for opt, arg in opts:
    if opt == "--id":
        AccessId = arg
    elif opt == "--key":
        AccessKey = arg
    elif opt == "--method":
        httpVerb = arg
    elif opt == "--url":
        url = arg
    elif opt == "--data":
        data = arg

#Construct resourcePath and remove /santaba/rest
resourcePath = urlparse(url).path

resourcePath = resourcePath[13:]

#Get current time in milliseconds
epoch = str(int(time.time() * 1000))

#Concatenate Request details
requestVars = httpVerb + epoch + data + resourcePath

#Construct signature
signature = base64.b64encode(hmac.new(AccessKey,msg=requestVars,digestmod=hashlib.sha256).hexdigest())

#Construct headers
auth = 'LMv1 ' + AccessId + ':' + signature + ':' + epoch
headers = {'Content-Type':'application/json','Authorization':auth}

#Make request
response = getattr(requests, httpVerb.lower())(url, data=data, headers=headers)

#Print status and body of response
print 'Response Status:',response.status_code
print 'Response Body:',response.content

sys.exit(2)

 

For example, the following command may be made from a terminal and uses the above script to retrieve all services in api.logicmonitor.com

python curl.py --id 'J62te62B8u7WnCR846h6' --key '{[H^LX=^Zg^32yp-x(-2Bq22vZ~^u-k3)8!9[7U^' --method 'GET' --url 'https://api.logicmonitor.com/santaba/rest/service/services'