简体   繁体   English

使用Python向REST API提交请求

[英]PUT Request to REST API using Python

For some reason my put request is not working and I am getting syntax errors. 由于某种原因,我的put请求无法正常工作,并且出现语法错误。 I am new to Python but I have my GET and POST requests working. 我是Python的新手,但我的GET和POST请求正在运行。 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'

Syntax error in because of = sign in your headers dictionary: 由于headers字典中的=符号,导致语法错误:

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 . 查看data=data已被'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? 或者你应该更换你的payloaddata在你put的要求吗?

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. 编辑完问题后,现在您将数据作为PUT请求的正文requests.put(data=data)发送,因此在标头中不需要它。 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 但是,由于您已将Content-Type标头设置为application/json所以我认为在您的PUT请求中您应该

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

that is send your data as json. 将您的数据作为json发送。

The problem is that you try to assign data to the data element in your dictionary: 问题是您尝试将data分配给字典中的data元素:

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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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