5

I would like to do a HTTP DELETE with python requests module that follows the API below;

https://thingspeak.com/docs/channels#create

DELETE https://api.thingspeak.com/channels/4/feeds
       api_key=XXXXXXXXXXXXXXXX

I am using python v2.7 and requests module. My python code looks like this;

def clear(channel_id):    
    data = {}
    data['api_key'] = 'DUCYS8xufsV613VX' 
    URL_delete = "http://api.thingspeak.com/channels/" + str(channel_id) + "/feeds"
    r = requests.delete(URL_delete, data)

The code does not work because requests.delete() can only accept one parameter. How should the correct code look like?

guagay_wk
  • 26,337
  • 54
  • 186
  • 295

2 Answers2

6

You want

import json
mydata = {}
mydata['api_key'] = "Jsa9i23jka"
r = requests.delete(URL_delete, data=json.dumps(mydata))

You have to use the named input, 'data', and I'm guessing that you actually want JSON dumped, so you have to convert your dictionary, 'mydata' to a json string. You can use json.dumps() for that.

I don't know the API you are using, but by the sound of it you actually want to pass URL parameter, not data, for that you need:

r = requests.delete(URL_delete, params=mydata)

No need to convert mydata dict to a json string.

Eugene K
  • 3,381
  • 2
  • 23
  • 36
  • Thanks! Tested to be the correct answer. The 2nd method works. One thing I do not understand. Why does `r = requests.delete(URL_delete, mydata)` fail but `r = requests.delete(URL_delete, params=mydata)` works? For HTTP Post, I do not need to use params. Why the difference? – guagay_wk Aug 28 '15 at 07:06
  • 4
    If you take a look at https://github.com/kennethreitz/requests/blob/master/requests/api.py. You can see that `post` is defined as `post(url, data=None ...)` whereas delete is defined as `delete(url, **kwargs)`. The kwargs means it has to be a 'keyed argument'. The post works cause it explicitly lists some arguments. – Eugene K Aug 28 '15 at 15:40
4

You can send the data params as @Eugene suggested, but conventionally delete requests only contains url and nothing else. The reason is that a RESTful url should uniquely identify the resource, thereby eliminating the need to provide additional parameters for deletion. On the other hand, if your 'APIKEY' has something to do with authentication, then it should be part of headers instead of request data, something like this.

headers = {'APIKEY': 'xxx'}
response = requests.delete(url, data=json.dumps(payload), headers=headers)
hspandher
  • 15,934
  • 2
  • 32
  • 45