requests.exceptions.HTTPError:400客户端错误:错误的url请求

时间:2019-06-28 17:36:15

标签: python json rest python-requests

我正在尝试使用Python请求在数据库中创建对象。我可以使用其他URL来执行此操作,但是对于这个特定的URL,我会遇到错误。我不确定实际的请求或URL是否有问题。创建需要四项内容,因此我现在只关注这些内容。

下面将根据文档找到请求有效负载的示例:

def create_opportunity(self, data):
    try:
        r = requests.post(
            self.URL + 'sales/opportunities', data=data,
            headers=self.Header)
        r.raise_for_status()
    except:
        raise
    return r.json()

create_opp = '{"name": "My Opportunity", "primarySalesRep": {"name": "John Doe"}, "company": {"name": "My Company"}, "contact": {"name": "Jane Doe"}}'

opportunity = objCW.create_opportunity(create_opp)

有效负载示例

{
  "name": "string",
  "primarySalesRep": {},
  "company": {},
  "contact": {}
}

primarsySalesRep

"primarySalesRep": {
    "id": 0,
    "identifier": "string",
    "name": "string",
    "_info": { }
},

公司

"company": {
    "id": 0,
    "identifier": "string",
    "name": "string",
    "_info": { }
},

联系人

"contact": {
    "id": 0,
    "name": "string",
    "_info": { }
},

1 个答案:

答案 0 :(得分:1)

在您的代码create_opp中是一个字符串。 data=的{​​{1}}函数的post()关键字中的You shouldn't pass a string

鉴于该服务器返回一个JSON(requests),我可以猜测它也接收到JSON。尝试执行以下操作:

return r.json()