Search code examples
pythonrestput

PUT Request to REST API using Python


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'

Solution

  • 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.