我正在使用 PoliteMail 的 ODATA RESTful API(文档:PoliteMail API Entity Directory)
我正在尝试使用 requests.post()
在 PoliteMail 中创建联系人。
下面是我的步骤
加载库
import requests
import json
# point to credentials
import os
import yaml
myKeys = yaml.load(open(os.path.join(os.path.expanduser('~'), 'Documents\keyfile2.json')))
身份验证凭证
user = myKeys['PoliteMail'][1]['user']
password = myKeys['PoliteMail'][1]['password']
auth = requests.auth.HTTPBasicAuth(user, password)
base_url = 'https://comm.microsoft.com/ssv3/odata/'
entity = 'Lists'
url = base_url+entity
获取请求
r = requests.get(url+'(56)', auth=auth)
print(r.status_code) # '200'
我可以获取此实体中的任何内容,但无法发布。
POST 请求
下面是结构given in the documentation
payload = {
"ID":"0",
"Name":"Test List",
"Description":"Does this work",
"IsNewsletter":"0",
"Shared":False,
"CreationDate":"2014-11-19T23:00:00.000Z",
"ActiveState":"1",
"isAnonymous":False,
"BusinessID":"0",
"RegionID":"0"
}
我的要求:
r = requests.post(url, data=json.dumps(payload),auth=auth)
输出
415: The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource."
但是当我为内容类型添加标题时:
r = requests.post(url, data=json.dumps(payload),auth=auth,
headers = {"Content-Type": "application/json"})
有人告诉我:
400 "The request is invalid." An error has occurred.\r\n","type":"","stacktrace":""
我尝试了以下方法,但无济于事:
json=
而不是data=
- 从 num 中删除引号
- 将 ID 值更改为 0 以外的值
- 从负载中删除换行符
非常感谢任何帮助!
更新
错误来自下面响应的解析文本是我使用 BeautifulSoup
时的完整响应读数
{
"odata.error":{
"code":"","message":{
"lang":"en-US","value":"The request is invalid."
},"innererror":{
"message":"contact : An error has occurred.\r\n","type":"","stacktrace":""
}
}
}
最佳答案
通过将 False 的大小写固定为 false 和isAnonymous 到负载中的 IsAnonymous。
{
"ID":"0",
"Name":"Test List",
"Description":"Does this work",
"IsNewsletter":"0",
"Shared":false,
"CreationDate":"2014-11-19T23:00:00.000Z",
"ActiveState":"1",
"IsAnonymous":false,
"BusinessID":"0",
"RegionID":"0"
}
您还提到在帖子开头创建联系人。我能够通过以下方式成功创建联系人。
{
"DisplayName": "Test Test",
"FirstName": "Test",
"LastName": "Test",
"Email": "test@politemail.com",
"ActiveState": true,
"CreationDate": "2017-09-12T0:49:23.303Z",
"Shared": false,
"OwnerID": 0,
"CategoryID": 8,
"StageID": 1,
"Company": "",
"WebAddress": "",
"Title": "",
"FileAs": "Test Test",
"Source": 0,
"Notes": "",
"Custom1": "",
"Custom2": "",
"Custom3": "",
"Custom4": "",
"Custom5": "",
"Custom6": "",
"Custom7": "",
"Custom8": "",
"Custom9": "",
"Custom10": "",
"Custom11": "",
"Custom12": "",
"Custom13": "",
"Custom14": "",
"Custom15": "",
"Custom16": "",
"Custom17": "",
"Custom18": "",
"Custom19": "",
"Custom20": "",
"BusinessID": 0,
"RegionID": 0,
"LastChangedDate": "2017-09-12T20:49:23.303Z",
"ListID": null
}
我在 PoliteMail 工作,并已提出内部请求以更新文档以修复 IsAnonymous 的大写。
更新:文档已更新为正确的大小写。 http://kb.politemail.com/?p=1349
关于python - 无效的帖子 : 400 - Bad Request with Python requests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46166950/