0 votes
1 view
in Python by (6.1k points)

I am attempting to write some python code to interact with New Relic's API. I'm using the requests module. For the most part I've been successful, but I'm having trouble with one API call. Their documentation represents the call with an example curl command:

https://docs.newrelic.com/docs/alerts/rest-api-alerts/new-relic-alerts-rest-api/rest-api-calls-new-relic-alerts (under "Update notification channels associated with policies")

curl -X PUT 'https://api.newrelic.com/v2/alerts_policy_channels.json' \

     -H 'X-Api-Key:{admin_api_key}' -i \

     -H 'Content-Type: application/json' \

     -G -d 'policy_id=policy_id&channel_ids=channel_id'

My main issue is that I am unclear how to translate the -G to python using the responses library. I'm not even totally sure I understand what that flag is doing, it sounds like it's making an additional get request in addition to the initial PUT?

I've been using this converter tool, which has worked for most curl calls I've been working with, but not this one.

https://curl.trillworks.com/

This is what's generated based off the above curl command (which does not work):

import requests

headers = {

    'X-Api-Key': '{admin_api_key}',

    'Content-Type': 'application/json',

}

data = {

  'policy_id': 'policy_id',

  'channel_ids': 'channel_id'

}

response = requests.put('https://api.newrelic.com/v2/alerts_policy_channels.json', headers=headers, data=data)

This is basically the same code, just wrapped in a function where I'm actually using it:

def set_alert_policy_notification_channel(admin_api_key, policy_id, notification_channel_id):

    headers = {

        'X-Api-Key': admin_api_key,

        'Content-Type': 'application/json',

    }

    data = {

    'policy_id': policy_id,

    'channel_ids': notification_channel_id

    }

    response = requests.put('https://api.newrelic.com/v2/alerts_policy_channels.json', headers=headers, data=data)

    logging.debug(response)

    return response

When I make the call I'm getting 500 errors, probably because the request is not formed properly:

2019-07-11 09:35:31,546 - DEBUG - Starting new HTTPS connection (1): api.newrelic.com:443 2019-07-11 09:35:32,046 - DEBUG - https://api.newrelic.com:443 "PUT /v2/alerts_policy_channels.json HTTP/1.1" 500 None 2019-07-11 09:35:32,293 - DEBUG -

1 Answer

0 votes
by (12.1k points)

You need to pass the data variable as the params argument in the request.put method. Like this: 

response = requests.put('https://api.newrelic.com/v2/alerts_policy_channels.json', headers=headers, params=data)

...