Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 832
guagay_wk Avatar asked Aug 28 '15 06:08

guagay_wk


People also ask

How do you send a delete request in Python?

The delete() method sends a DELETE request to the specified url. DELETE requests are made for deleting the specified resource (file, record etc).

Is there a delete method in Python?

The del keyword in python is primarily used to delete objects in Python. Since everything in python represents an object in one way or another, The del keyword can also be used to delete a list, slice a list, delete a dictionaries, remove key-value pairs from a dictionary, delete variables, etc.

How does requests module work in Python?

The requests module allows you to send HTTP requests using Python. The HTTP request returns a Response Object with all the response data (content, encoding, status, etc).


1 Answers

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.

like image 69
Eugene K Avatar answered Sep 21 '22 16:09

Eugene K