简体   繁体   中英

HTTP Delete with python requests module

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?

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM