【问题标题】:requests.exceptions.HTTPError: 400 Client Error: Bad Request for urlrequests.exceptions.HTTPError:400 客户端错误:对 url 的错误请求
【发布时间】:2019-11-10 15:52:05
【问题描述】:

我正在尝试使用 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": { }
},

【问题讨论】:

    标签: python json rest python-requests


    【解决方案1】:

    在您的代码中,create_opp 是一个字符串。 You shouldn't pass a stringpost()data= 关键字requests 的函数中。

    鉴于该服务器返回 JSON (return r.json()),我猜它也接收 JSON。尝试做这样的事情:

    def create_opportunity(self, data):
        r = requests.post(self.URL + 'sales/opportunities', json=data, headers=self.Header)
        r.raise_for_status()
        return r.json()
    
    create_opp = {
        "name": "My Opportunity", 
        "primarySalesRep": {"name": "John Doe"},  # maybe "id" or "identifier" is required? 
        "company": {"name": "My Company"},  # maybe "id" or "identifier" is required? 
        "contact": {"name": "Jane Doe"},
    }
    
    opportunity = objCW.create_opportunity(create_opp)
    

    【讨论】:

      猜你喜欢
      • 2019-05-15
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多