Accessing the LogicMonitor REST API with Postman and LMv1 API Token Authentication
Introduction Postmanis widely used for interacting with various REST APIs such as LogicMonitor's. However, there is no out-of-the-box support for the LMv1 authentication method which we recommend as a best practice. This document describes how to configure Postman to use LMv1 authentication when interacting with our REST API. Overview Postman'spre-request script functionalityprovides the ability to generate the necessary Authorization header for LMv1 authentication. As the name suggests, the pre-request script runs immediately before the request is made to the API endpoint. We set the pre-request script at the collection level in Postman so that it will run automatically for every request that is part of the collection. The script requires three input parameters: a LogicMonitor API token (or ID), its associated key, and the full request URL. These parameters are made available to the script by creating a Postman environment and setting the values as environment variables. If you need to access multiple LogicMonitor accounts (portals), create a separate environment for each to store the applicable API and URL information. Since all API requests to a given account use the same base URL (https://<account>.logicmonitor.com/santaba/rest) it is convenient to store this as an environment variable. The output of the script is the value of the Authorization header. The script writes the header value to an environment variable which is then inserted as the Authorization header value in the request. Instructions 1. Download and installPostman. 2. Launch Postman andcreate a new collectionthat will be used for all LogicMonitor API requests. 3. In the create collection dialog, select the "Pre-request Scripts" section and paste in the following code. // Get API credentials from environment variablesvar api_id = pm.environment.get('api_id');var api_key = pm.environment.get('api_key'); // Get the HTTP method from the requestvar http_verb = request.method; // Extract the resource path from the request URLvar resource_path = request.url.replace(/(^{{url}})([^\?]+)(\?.*)?/, '$2'); // Get the current time in epoch formatvar epoch = (new Date()).getTime(); // If the request includes a payload, included it in the request variablesvar request_vars = (http_verb == 'GET'||http_verb == 'DELETE') ?http_verb + epoch + resource_path : http_verb + epoch + request.data + resource_path; // Generate the signature and build the Auth headervar signature = btoa(CryptoJS.HmacSHA256(request_vars,api_key).toString());var auth = "LMv1 " + api_id + ":" + signature + ":" + epoch; // Write the Auth header to the environment variablepm.environment.set('auth', auth); 4. Create anew environment. Create the environment variables shown below. You do not need to provide a value for the "auth" variable since this will be set by the pre-request script. Be sure to use the api_id, api_key, and url values appropriate for your LogicMonitor account. 5. Create arequestand add it to the collection with the pre-request script. A sample request is shown below with the necessary parameters configured. 1. Set the environment for the request, 2. Set the HTTP method for the request. 3. Use{{url}} to pull the base URL from the environment variable. Add the resource path and any request parameters your API request may require. 4. Add the Authorization header and set the value to{{auth}}to pull the the value from the environment variable. 5. POST, PUT, and PATCH requests only: if your request includes JSON data, be sure to select the Body tab and add it. 6. Press Send to send the request. The response will appear below the request in Postman. Troubleshooting You receive the response "HTTP Status 401 - Unauthorized" Confirm the following: • The proper environment has been specified for the request. • The necessary environment variables have been set and their values are correct. Note that the script relies on the specific variable names used in this document: "api_id", "api_key", "url", and "auth". • The request is a member of the collection configured with the pre-request script. Postman reports "Could not get any response" or "There was an error in evaluating the Pre-request Script: TypeError: Cannot read property 'sigBytes' of undefined" Make sure you have set the proper environment for the request and all necessary environment variables and values are present.3.6KViews43likes42CommentsPowershell: Expanding a variable inside single quotes to make an API call
Hi, I’m trying to use Powershell to make an API call and pass in the SDT start/end time as a variable. However, because the call has to be within single quotes, I can’t get it to expand the variable. I have $now set to the epoch time of now and $later set to the epoch time two hours later. I’m trying to make a call with something like: '{"sdtType":1,"type":"DeviceSDT","deviceId":13771,"startDateTime":$now,"endDateTime":$later}' Because the whole string is within a single quote, I can’t get PS to parse out the two variables and use their data. I tried escaping the quotes and also using -f formatting, but can’t get anything to work. Just wondering if anyone here knows how I can make this happen. I tried swapping all the single and double quotes, which lets the Powershell work, but then the API fails because it requires double quotes to be surround the field names and won't accept single quotes. Thanks.Solved800Views13likes4CommentsHow do I configure Postman AUthentication for API
HI, I’m relatively new to Postman and API calls but have a decent grasp on how they work. However, I can’t figure out how to handle the Authentication part within LM. I read through the various KB articles but didn’t find a step-by-step which is what I need for this one. I was able to grab my ID and Key from our portal, but I’m not sure where I put them in Postman. Do I create them as variables and then add them as parameters somehow? I made a Collection for LM, but when I edit it and go to the Authentication area, I’m not sure which item to choose as none seem to let me put in an ID and a Key. Can anyone help me with how I get this setup? Thanks.599Views3likes11CommentsUsing Postman to create multiple Websites via API & CSV?
Hi, I’m testing out creating websites (or resources) via the API. I have a standard Post working in Postman just fine. However, when I then try to do the same thing via a CSV file in the Runner section, I’m getting 401 Authorization errors. When I look at the data that’s being sent, it looks the same as what’s sent when I run it manually. Is there something special I need to do when running a Post command via the Runner vs the manual Send command? Thanks.Solved500Views12likes40CommentsTrouble Authenticating to LogicMonitor REST API from ServiceNow
I am trying to convert a PowerShell script to run from ServiceNow and found “Using REST API from ServiceNow Scripting” from two years ago. Since then, ServiceNow has addedGlideDigest() which, among other things, should allow me to create a message digest from a string using the SHA256 algorithm, with the result being a Base64 string. However, I am getting back: "{"errorMessage":"Authentication failed","errorCode":1401,"errorDetail":null}" The PowerShell script looks like this: [string]$sandboxaccessid = 'abc' [securestring]$sandboxaccesskey = '123' | ConvertTo-SecureString -AsPlainText -Force [string]$AccountName = 'portalname' [int]$Id = 2 $httpVerb = "GET" $resourcePath = "/device/devices/$id" $AllProtocols = [System.Net.SecurityProtocolType]'Tls11,Tls12' [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols $time = (Get-Date).ToUniversalTime() $epoch = [Math]::Round((New-TimeSpan -Start (Get-Date -Date "1/1/1970") -End $time).TotalMilliseconds) $requestVars = $httpVerb + $epoch + $resourcePath $hmac = New-Object System.Security.Cryptography.HMACSHA256 $hmac.Key = [Text.Encoding]::UTF8.GetBytes([System.Runtime.InteropServices.Marshal]::PtrToStringAuto(([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sandboxaccesskey)))) $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())) $headers = @{ "Authorization" = "LMv1 $sandboxaccessid`:$signature`:$epoch" "Content-Type" = "application/json" "X-Version" = 3 } $url = "https://$AccountName.logicmonitor.com/santaba/rest$resourcePath" $response = Invoke-RestMethod -Uri $url -Method $httpVerb -Header $headers -ErrorAction Stop $resposne And JavaScript looks like this (at the moment): var ACCESS_ID = 'abc'; var ACCESS_KEY = '123'; var ACCOUNT_NAME = 'portalname'; var resourcePath = '/device/devices'; var time = new Date().getTime(); var epoch = Math.round((time - new Date("1/1/1970").getTime())); var id = 2; var requestVars = 'GET' + epoch + resourcePath; // Compute the HMACSHA256 hash using GlideDigest var gd = new GlideDigest(); var signature = gd.getSHA256Base64(ACCESS_KEY, requestVars); // Remove hyphens from the signature signature = signature.replace(/-/g, ''); var token = 'LMv1 ' + ACCESS_ID + ':' + signature + ':' + epoch; var httpRequest = new GlideHTTPRequest('https://' + ACCOUNT_NAME + '.logicmonitor.com/santaba/rest/device/devices/' + id); httpRequest.addHeader('Content-Type', 'application/json'); httpRequest.addHeader('Authorization', token); httpRequest.addHeader('X-Version', '3'); var response = httpRequest.get(); gs.info('Response status code: ' + response.getStatusCode()); gs.info('Devices = ' + response.body); Anyone know how to make this authentication work, without the customerconvertByteArrayToHex() utility?Solved400Views10likes7CommentsExperience the new API v3
As you all know, we have implemented all the latest enhancements in LogicMonitor REST API v3 ONLY. Some of the key features that work only with API v3 are: Advance filtering to get accurate result Bearer token for authentication Delta feature on device\devices endpoint (coming soon…) To start using all these features, we strongly recommend you to upgrade to LogicMonitor API v3 as the base version in your environment. For more details, refer to the following support articles: REST API v3 Swagger doc: https://www.logicmonitor.com/support/v3-swagger-documentation REST API v3 Advanced filtering: https://www.logicmonitor.com/support/rest-api-advanced-filters Bearer token with REST API v3: https://www.logicmonitor.com/support/bearer-token399Views33likes7CommentsUnable to authenticate Rest api with servicenow to get devices
Hi All, I am trying to authenticate in servicenow using script but it is not working. It is throwing an error authentication failed status 401. var ACCESS_ID = '123'; var ACCESS_KEY = 'abc'; var ACCOUNT_NAME = 'test'; var resourcePath = '/device/devices'; var epoch = (new Date()).getTime(); var id = 2; var requestVars = 'GET' + epoch + resourcePath; var HexUtil = { convertByteArrayToHex : function(byteArray) { var hex = ""; byteArray.forEach(function(byteValue) { hex += HexUtil.convertByteToHex(byteValue); }); return hex; }, convertByteToHex : function(b) { var hexChar = ["0", "1", "2", "3", "4", "5", "6", "7","8", "9", "a", "b", "c", "d", "e", "f"]; return hexChar[(b >> 4) & 0x0f] + hexChar[b & 0x0f]; } }; // Compute the HMACSHA256 hash using GlideDigest var key = "key"; key = encodeURIComponent(key); key = GlideStringUtil.base64Encode(key); var msg = "message"; msg = encodeURIComponent(msg); var mac = new GlideCertificateEncryption(); signature = mac.generateMac(requestVars, "HmacSHA256", ACCESS_ID); var bytes = GlideStringUtil.base64DecodeAsBytes(signature); var hex = HexUtil.convertByteArrayToHex(bytes); var hexB64 = GlideStringUtil.base64Encode(hex); var token = 'LMv1 ' + ACCESS_ID + ':' + signature + ':' + epoch; gs.info('Devices = ' +token); var httpRequest = new GlideHTTPRequest('https://' + ACCOUNT_NAME + '.logicmonitor.com/santaba/rest/device/devices'); httpRequest.addHeader('Content-Type', 'application/json'); httpRequest.addHeader('Authorization', token); //httpRequest.addHeader('x-server-version', '3'); var response = httpRequest.getBody(); gs.log(response); Could you please help me on this.300Views4likes3CommentsCan I pull a specific system property in an API call?
Hi, I’m writing an API call that pulls only specific fields. I can get all the normal fields, but I want to get system.groups. System.groups is inside the systemProperties array of variables and I haven’t been able to figure out if I can pull it. I’m using: &fields=name,displayName,collectorDescription,hostStatus and want to add systemProperties[system.groups] but can’t find any syntax that will work. I’ve found examples on how to Filter on a property, but not how to just display it. Anyone know how I can do this? Thanks.300Views3likes10CommentsAlerts API - Size Limit
Hi Everyone, I am running into a size limit issue in my pursuit of creating a quarterly report for a customer. What I am trying to do is narrow down my filter to have any cleared alert that is a severity 4 that was closed during that quarter. My issue is two-fold. I am not sure of the syntax that would only show alerts that cleared during that quarter (I am trying to do the equivalent of ‘between’ in python IF statements)and the size limit of 1000 is limiting because I cannot get a count of cleared alerts. I couldn’t find anything regarding pagination that can be used. I have also attempted to do the F12 then network button trick, but there is nothing that stands out there or anything that I can identify. And I have tried looking at other questions and couldn’t find anything relating this. This is my query: ?size=1000&filter=severity:4,cleared:true,startEpoch>:{startEpoch}&filter=severity:4,cleared:true,endEpoch<:{endEpoch} Any guidance would be greatly appreciated.Solved299Views2likes2CommentsAPI Method to CLEAR an Alert (toggle off=on Alert Enable)
Hello, We have a need to via API, CLEAR an alert. I don’t see any API Methods to clear an alert. I only see methods to GET or POST a Note/ACK. Can you assist me with what API method we can use to clear (toggle on/off) an alert? Thanks, Darren Dudgeon298Views1like13Comments