Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PUT Request to REST API using Python

Tags:

python

rest

put

For some reason my put request is not working and I am getting syntax errors. I am new to Python but I have my GET and POST requests working. Does anyone see anything wrong with this request and any recommendations? I am trying to change the description to "Changed Description"

PUT

#import requests library for making REST calls
import requests
import json

#specify url
url = 'my URL'

token = "my token"

data = {
        "agentName": "myAgentName",
        "agentId": "20",
        "description": "Changed Description",
        "platform": "Windows"
        }

headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", data:data}

#Call REST API
response = requests.put(url, data=data, headers=headers)

#Print Response
print(response.text)

Here is the error I am getting.

Traceback (most recent call last):
  line 17, in <module>
    headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", data:data}
TypeError: unhashable type: 'dict'
like image 999
Tim Avatar asked Oct 14 '15 14:10

Tim


2 Answers

Syntax error in because of = sign in your headers dictionary:

headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", data=data}

It should be:

headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", 'data':data}

See data=data is changed with 'data':data. Colon and Single Quotes.

And are you sure you will be sending data in your headers? Or you should replace your payload with data in your put request?

Edit:

As you have edited the question and now you are sending data as PUT request's body requests.put(data=data) so there is no need of it in headers. Just change your headers to:

headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json"}

But as you have set your Content-Type header to application/json so I think in your PUT request you should do

response = requests.put(url, data=json.dumps(data), headers=headers)

that is send your data as json.

like image 105
Muhammad Tahir Avatar answered Oct 14 '22 23:10

Muhammad Tahir


The problem is that you try to assign data to the data element in your dictionary:

headers = { ..., data:data }

That can't work because you can't use a dictionary as a key in a dictionary (technically, because it's not hashable).

You probably wanted to do

headers = { ..., "data":data }
like image 31
Marcus Müller Avatar answered Oct 14 '22 23:10

Marcus Müller