Forum Discussion

cuotos's avatar
8 years ago

Add device to group API

I'm trying to find the right way to add an existing device to an existing group via the REST API.

I've tried PATCHing / PUTing the hostGroupIds field of the device but that doesnt work, and I get the following. 

"errmsg" : "Property(name=hostGroupIds) cannot be found in device(id=1504)'s own property"

Should I add the group ID to the device, or can I edit the devices in a Group via the API?

 

  • Sarah_Terry's avatar
    Sarah_Terry
    Icon for Product Manager rankProduct Manager

    The recommended method is to update the hostGroupIds field for the device.  If you only want to change the device's group membership, a PATCH request makes the most sense.  If you're adding the device to a group, but want it to remain in the existing groups, you'll likely want to make a GET request first, and just tack the new group id onto the end.  Here's an example of updating a device's group membership (in Python):

    #!/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 ='PATCH'
    resourcePath = '/device/devices/637'
    queryParams ='?patchFields=hostGroupIds'
    data = '{"hostGroupIds":"59,6,115"}'
    
    #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
    signature = base64.b64encode(hmac.new(AccessKey,msg=requestVars,digestmod=hashlib.sha256).hexdigest())
    
    #Construct headers
    auth = 'LMv1 ' + AccessId + ':' + signature + ':' + epoch
    headers = {'Content-Type':'application/json','Accept':'application/json','Authorization':auth}
    
    #Make request
    response = requests.patch(url, data=data, headers=headers)
    
    #Print status and body of response
    print 'Response Status:',response.status_code
    print 'Response Body:',response.content

     

    Note that the hostGroupIds field is called out in the patchFields query parameter, as well as in the payload.  Is this what you attempted to do?  If so, if you share your code I can help identify what went wrong.  

    Thanks!

    Sarah