Search the Community

Showing results for tags 'REST'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


  • From LogicMonitor
    • General Announcements
    • LM Staff Contributions
    • Community Events
  • LogicMonitor Product Discussion
    • Feature Requests
    • LM Exchange
    • Ask the Community

Find results in...

Find results that contain...

Date Created

  • Start


Last Updated

  • Start


Filter by number of...


  • Start



About Me

Found 17 results

  1. Trying to schedule a new SDT for January 1, 2018 1:00 AM to 1:30 AM for a device group, but getting a Status:1007 and a blank response. <# account info #> $accessId = 'SHj6Hub8e63FUwkc5' $accessKey = 'xz37=(][{qb6ANLp}5$-S9Hvn6HV292P' $company = 'api' # stdTYpe (integer) # 1 - one time, 2 - Weekly SDT, 3 - Monthly SDT, 4 - Daily SDT # we have to use "one time" style values because LM has no concept of day of month $stdTYpe = 1 # type (string) # ServiceGroupSDT, DeviceGroupSDT, CollectorSDT $type = "DeviceGroupSDT" # deviceGroupId (string) # $deviceGroupId = 18 # dataSourceId (integer) # 0 = ALL $dataSourceId = 0 <# request details #> $httpVerb = 'POST' $resourcePath = '/sdt/sdts' #serviceGroupSDTs # data $data = '{"sdtType":'+$stdTYpe+',"type":"'+ $type +'","deviceGroupId":'+ $deviceGroupId +',"dataSourceId":'+ $dataSourceId +',"startDateTime":1514786400,"endDateTime":1514788200}' <# Construct URL #> $url = 'https://' + $company + '' + $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 = $| ConvertTo-Json -Depth 5 Write-Host "Status:$status" Write-Host "Response:$body"
  2. I took a working groovy script datasource and am now trying to adjust it to some needs we have. This data will end up giving us alert totals for each month so we can build reports. Any ideas? Here is what I have so far. import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Hex; import groovy.json.JsonSlurper; //define credentials and url def accessId = hostProps.get(''); def accessKey = hostProps.get('lmaccess.key'); def account = hostProps.get('lmaccount'); def alertgroup = hostProps.get(''); def collectionFailures = 0 def failures = [:] def client = new LogicMonitorRestClient(accessId, accessKey, account, this.&println) try { def alerts = client.get("/device/groups/" + alertgroup + "/alerts", fields: "severity", filter: "startEpoch>:1538370000,endEpoch<:1541048399,cleared:*") //warnings = alerts.findAll {it.severity == 2}.size() println "WarningCount: ${alerts.findAll {it.severity == 2}.size()}" println "ErrorCount: ${alerts.findAll { it.severity == 3 }.size()}" println "CriticalCount: ${alerts.findAll { it.severity == 4 }.size()}" println "TotalAlerts: ${alerts.size()}" } catch (Throwable e) { failures["alerts"] = e.toString() collectionFailures += 1 } // Do error reporting println "CollectionFailures:${collectionFailures}" failures.each{ query, exception -> println "Exception while querying $query:" println exception } return 0 ////////////////////// // HELPER FUNCTIONS // ////////////////////// class LogicMonitorRestClient { String userKey String userId String account int maxPages = 20 int itemsPerPage = 1000 def println LogicMonitorRestClient(userId, userKey, account, printFunction) { this.userId = userId this.userKey = userKey this.account = account this.println = printFunction } def generateHeaders(verb, path) { def headers = [:] def epoch = System.currentTimeMillis() def requestVars = verb + epoch + path // Calculate signature def hmac = Mac.getInstance('HmacSHA256') def secret = new SecretKeySpec(userKey.getBytes(), 'HmacSHA256') hmac.init(secret) // Sign the request def hmac_signed = Hex.encodeHexString(hmac.doFinal(requestVars.getBytes())) def signature = hmac_signed.bytes.encodeBase64() headers["Authorization"] = "LMv1 " + userId + ":" + signature + ":" + epoch headers["Content-Type"] = "application/json" return headers } def packParams(params) { def pairs = [] params.each{ k, v -> pairs << ("${k}=${v}")} return pairs.join("&") } // Non paginating, raw version of the get function def _rawGet(path, params) { def baseUrl = 'https://' + account + '' + '/santaba/rest' + path def packedParams = "" if(params) { packedParams = "?"+packParams(params) } def query = baseUrl+packedParams def url = query.toURL() def response = url.getText(useCaches: true, allowUserInteraction: false, requestProperties: generateHeaders("GET", path)) return response } // Public interface for getting stuff. def get(Map args=[:], path) { def itemsReceived = [] def pageReads = 0 // Impose our own paging parameters. args.size = itemsPerPage args.offset = 0 while(true) { // Do da nastieh def response = new JsonSlurper().parseText(_rawGet(path, args)) if (response.errmsg == "OK") { // Catch individual items if ( == null) { return } itemsReceived += // Check if there are more items // if ( > itemsReceived.size()) // { args.offset = args.size + args.offset // } // else // { // break // we are done // } } else { // Throw an exception with whatever error message we got. throw new Exception(response.errmsg) } pageReads += 1 // Check that we don't exceed max pages. if (pageReads >= maxPages) { break } if ( > 0) { break } } return itemsReceived } } If I run the URL with the API creds in my test powershell script, it works perfectly. When I test it in LM as a datasource, I get the attached error.
  3. It would be nice to have a swagger doc to define all the rest endpoints. We are developing a graphql server internally and it would be useful to be able to programmatically define the LogicMonitor portion. I see that LM has a swagger project in github not quite sure the scope of that, but an example of a swagger doc that can be read and interpreted comes from connectwise manage:
  4. I am attempting to adjust an escalation chain via PowerShell and REST. I am currently getting back a 1007 and can't seem to figure out what is wrong. Below is what I am using, I have tried different forms of $data. Our main goal is to change CC. We have tried these two and then the 1 in the script below. Just not sure what is coming up wrong. $data = '"ccDestinations":[{"type":"arbitrary","method":"email","addr":""}]' $data = '"destinations":[{"type":"single","stages":[[{"type":"arbitrary","method":"email","addr":""}]]}]' <# Use TLS 1.2 #> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 <# account info #> $accessId = '' $accessKey = '' $company = '' <# request details #> $httpVerb = 'PUT' $resourcePath = '/setting/alert/chains/4' $data = '"name":"Chain 1","ccDestinations":[{"type":"arbitrary","method":"email","addr":""}],"destinations":[{"type":"single","stages":[[{"type":"arbitrary","method":"email","addr":""}]]}]' <# Construct URL #> $url = 'https://' + $company + '' + $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 $status $body = $ | ConvertTo-Json -Depth 5 $body
  5. I have created a Groovy script based PropertySource, that uses a REST call to contact an external site using the included HTTP helper methods in order to fill some information fields. This works fine in itself. The issue I have is the need to set the proxy details on the object after it is instantiated in the script. As far as I know, the collector properties/settings are not exposed in any way to a scripted PropertySource, despite the script running locally on the collector. Nor does the HTTP connection use the existing proxy as set on the collector. Unless I am missing something, it seems exceptionally convoluted to get those details, and then propagate them into property fields for all devices on that collector. to then be able to reference them properly inside the script. Is there any way to call the equivalent of getHostProps(), but for the collector properties? This would also be useful in cases of say, independent customer sites that use separate API keys for the same script.
  6. I have the below code which results in a 401. Any ideas? I am attempting to update the hostGroupIds. $status = $null $body = $null $response = $null <# Use TLS 1.2 #> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 <# account info #> $accessId = '*****' $accessKey = '*****' $company = '*****' <# request details #> $httpVerb = 'PATCH' $resourcePath = '/device/devices/1210' $queryParams = '?patchFields=hostGroupIds' $data = '{"hostGroupIds":"187,258"}' <# Construct URL #> $url = 'https://' + $company + '' + $resourcePath + $queryParams <# 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 -Header $headers <# Print status and body of response #> $status = $response.status $body = $ | ConvertTo-Json -Depth 5 $devices = $ $status $body
  7. Hello all, I am trying to get updates on alerts that span multiple days. So, our normal code will grab new alert data for today, let's say. However, we need to go back to old alerts and see if they have been resolved yet, so we can do accurate reporting. What I want to do is provide a list of the IDs for a handful of alerts and get more than 1 row back. Any ideas on how I can formulate an alert query so that I can get 2 rows back for, say ID=DS1234567 and ID=1234568 in the same request? Here is my example call:,id:DS1472582 My hope is to combine a batch of calls so I don't flood the service and so I can get results faster. Given a list of unique IDs, any thoughts on requesting a batch? E
  8. I was testing the new rate limiting feature that was to be rolled out v99 and enacted in v100. Turns out Powershell throws out the headers when calling the invoke-restmethod commandlet unless an exception is thrown - this would mean I need to re-write all of my REST API scripts in another language or change to invoke-webrequest. It would make it to adapt to the rate limiting for us PowerShell users easier if this data was just included in the response content.
  9. Hi, Is there a way to get all instances for given data source, but without having to provide device IDs? The REST API offers the following URI: URI: /device/devices/{deviceId}/devicedatasources/{deviceDatasourceId}/instances What I need is the equivalent of something like this: URI: /datasource/datasources/{datasourceId}/instances Which would return all instances for the datasource from all devices that have the datasource. The returned data should include the "managedObjectName" property so that from the instance we can refer back to a device.
  10. I discovered that when making REST API calls if there is no data available for the period requested, then the output is blank as in nothing. This should be revised to No Data, or some other value to indicate. Especially when requesting data in a CSV format - there should at least be the correct number of ',' in the output to - if there are 5 rows of no data in the output, it should result in ',,,,' or 'no data,no data,no data,no data,no data' as the output.
  11. I've been trying to get data for individual datapoints within a single instance datasource via the REST API, in this case there are ~twenty datapoints and I only want data for one of them. Using get_data: I can pick out my datasource, however I can't find any information on filtering by datapoint. When I get data, the datapoints are all listed in an array, then the data is presented as an array of arrays for the last hour...I could get the position of the datapoint in the first array, then pick out the data using that position for each array listed in the data but that feels like a bad road to travel. query is essentially: "resourcePath = '/device/devices/73023/devicedatasources/1573061/instances/1928726/data'" Right now I'm adding the datapoints I want to a custom graph, I can then pull out the data for that custom graph e.g. "resourcePath = '/device/devices/73023/devicedatasources/1573061/instances/1928726/graphs/3133/data'" (with multiple lines I can pick specific data by checking the line label). Although this works fine, it still feel like an additional step. What I'd really like is: "resourcePath = '/device/devices/73023/devicedatasources/1573061/instances/1928726/ [datapoint/datapointID] /data'" but I can't see an ID for datapoints or an option for putting a 'name' in. Have I missed something? Does anyone already do this in a simple way?
  12. Is it possible to pull a devices' through the REST API?
  13. Anyone know how to pull a list of ALL devices (1000s) with instances reporting "No Data" via the REST API? Thanks as always!
  14. Looking to add 200+ Websites to be monitored via the Services. Has anyone created a script to read the required variables from a csv file? Thanks in advance for any assistance!
  15. Currently there is no hostName parameter available for the REST API though it exists in the RPC API. When retrieving information about a device using the 'devices/device' endpoint using the REST API: /devices/device/?filter=deviceType:0,name~<some ipv4 address>,size:1 There is a chance that the device being returned is actually another device when using the ~ operator against the name of the device. There would be quite a bit of work to wildcard filter by name and would be different depending on the tenant's naming schema. Adding the hostName parameter as a feature would mirror RPC's functionality and save quite a bit of custom code from being written. If anyone is aware of how to filter by hostName or similar (ipv4) parameter without additional operations please let me know.
  16. So this is less of an ask the community and more of a show the community. Ive written some Ruby code that makes it much much easier to use the LogicMonitor API. It does all the signing for you so you can just focus on your API calls and worry less about the secure signing. It uses the following rest-client library and injects the authentication method into the rest-client library. Ive included some examples of usage in my gist. Let me know if your having difficulty and i will test and patch as needed For an example of how easy this makes using the Rest API temp_url = @URL + '/service/services' response = RestClient.get(temp_url) # Printing API server response puts "\nServer response: #{response}"
  17. Trying to get "serviceProperties" to populate when pulled via the REST API. I add a Properties entry on a Web Service Check: Name - [account_name], Value - [TheoretDevelopment] but the results always come back empty. Tried various options. Does the REST API actually support this field? Any assistance would be much appreciated. Thank you! serviceProperties The properties associated with the Service JSON Object "serviceProperties" : [ {"name" : "billing","value" : "website"}, {"name" : "team","value" : "TechOps"}, {"name" : "production","value" : "true"} ] { "type": "webservice", "id": 177, "name": "", "description": "If this site goes down, follow standard critical alert procedures per the client policy", "serviceFolderId": 247, "stopMonitoring": false, "stopMonitoringByFolder": false, "disableAlerting": false, "individualSmAlertEnable": false, "individualAlertLevel": "warn", "overallAlertLevel": "critical", "alertStatus": "none", "alertStatusPriority": 100000, "sdtStatus": "none-none-none", "alertDisableStatus": "none-none-none", "pollingInterval": 1, "transition": 9, "testLocation": "{\"all\":false,\"smgIds\":[1,2]}", "globalSmAlertCond": 0, "useDefaultLocationSetting": false, "useDefaultAlertSetting": false, "userPermission": "write", "checkpoints": " ", "serviceProperties": "", "serviceStatus": "alive", "isInternal": false, "collectors": "", "script": "", "method": "tabledriven", "ignoreSSL": true, "pageLoadAlertTimeInMS": 30000, "steps": "" },