Come join our live training webinar every other Wednesday at 11am PST and hear LogicMonitor experts explain best practices and answer common questions. We understand these are uncertain times, and we are here to help!
The following examples illustrate LMv1 Authentication for LogicMonitor REST API v1.
NOTE: These examples are provided for illustration purposes. Before you use them, you may need to edit parameters for your implementation.
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 ='API-ACCESS-ID' AccessKey ='API-ACCESS-KEY' 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
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 ='API-ACCESS-ID' AccessKey ='API-ACCESS-KEY' 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
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 ='API-ACCESS-ID' AccessKey ='API-ACCESS-KEY' 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 digest = hmac.new( AccessKey.encode('utf-8'), msg=requestVars.encode('utf-8'), digestmod=hashlib.sha256 ).hexdigest()signature = base64.b64encode(digest.encode('utf-8')).decode('utf-8')# Construct headers auth = 'LMv1 ' + AccessId + ':' + str(signature) + ':' + epoch print(auth) (edited) 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)
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 = 'API-ACCESS-ID'; def accessKey = 'API-ACCESS-KEY''; 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();
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 = 'API-ACCESS-ID'; def accessKey = 'API-ACCESS-KEY'; 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();
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 = 'API-ACCESS-ID' $accessKey = 'API-ACCESS-KEY' $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"
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 = 'API-ACCESS-ID' $accessKey = 'API-ACCESS-KEY' $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"
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 = 'API-ACCESS-ID' @access_key = 'API-ACCESS-KEY' @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
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 = 'API-ACCESS-ID' @access_key = 'API-ACCESS-KEY' @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
The following PHP script adds an alert rule to account api.logicmonitor.com:
<?php $accessID = 'your-access-id'; $accessKEY = 'your-access-key'; $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); ?>
The following Node.js script gets the name and id of all devices with “prod” in the name from account api.logicmonitor.com:
// Account Info var accessId = 'your-access-id'; var accessKey = 'your-access-key'; 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) } });
To use a cURL command or other one line request against the REST API v1, you will need to run the command in the following format:
python scriptName.py --id --key --method --url --data [Request Payload]
An example script may be:
#!/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)
The following command can be run from a terminal and uses the above script to retrieve all services in api.logicmonitor.com:
python curl.py --id 'ACCESS-ID' --key 'ACCESS-KEY' --method 'GET' --url 'https://api.logicmonitor.com/santaba/rest/service/services'
In This Article