【问题标题】:Empty body error on post request in python scriptpython脚本中发布请求的空正文错误
【发布时间】:2020-01-29 14:26:52
【问题描述】:

我正在尝试使用 python 和请求向 API 端点发出发布请求。 端点需要一个令牌。我从端点获取令牌就好了。

当向第二个端点发出发布请求时,验证错误表明正文为空。

import requests

url = "https://authz.dinero.dk/dineroapi/oauth/token"
payload = 'grant_type=password&username=****&password=****'
headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Authorization': 'Basic ****'
}

response = requests.request("POST", url, headers=headers, data = payload)
r =response.json()
token = r['access_token']

url = "https://api.dinero.dk/v1/257403/contacts"
payload = {}
payload["Name"]  = "Test Name"
payload["CountryKey"] = "DK"
payload["IsPerson"] = "true"

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

response = requests.post(url, headers=headers, data = payload)
print(response.text)

这是我得到的错误:

{"code":42,"message":"验证错误","validationErrors":{"Body":"正文为空"},"languageSpecificMessages":[{"property":"message", "message":"Der er fejl i de angivne data"},{"property":"Body","message":"正文为空"}],"errorMessageList":[{"Code":"Body" ,"Message":"正文是空的"}]}

这是从邮递员那里获取的相同代码。它工作正常。

import requests
url = "https://api.dinero.dk/v1/257403/contacts"
payload = "{\r\n  \"Name\": \"Test Name\",\r\n  \"CountryKey\": \"DK\",\r\n  \"IsPerson\": true\r\n}"
print(payload)
headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ****'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))

我希望有人能解释为什么我的代码不起作用。

【问题讨论】:

  • 您可能需要先将 payload 转储到 JSON 字符串 (json.dumps(payload)) 而不是传递字典。至少这就是我可以在两个 sn-ps 中发现的区别。
  • 您的邮递员示例将有效负载作为 JSON 字符串,而您的第一个示例将其作为字典。您可以尝试将 dict 作为 json= 参数传递给 requests.post。

标签: python python-requests


【解决方案1】:

Requests 有一个可以使用的 json= 参数:

response = requests.post(url, headers=headers, json=payload)

文档here.

【讨论】:

    【解决方案2】:

    在您的第二次通话中,您希望 json 转储有效负载:

    import json
    
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    

    Postman 已经将有效负载序列化为 json 格式的字符串。您可以对json.dumps() 执行相同操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      相关资源
      最近更新 更多