6

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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
If you take a look at 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.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.