简体   繁体   中英

requests.exceptions.HTTPError: 400 Client Error: Bad Request for url

I am trying to create an object in a database using Python requests. I am able to do this with other URLs, but for this particular one I am getting errors. I am not sure if there is a problem with the actual request or the URL. Four items are required for creation, so I will just focus on those for now.

Below you will find an example of the request payload according to the documentation:

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)

payload example

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

primarsySalesRep

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

company

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

contact

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

In your code create_opp is a string. You shouldn't pass a string in data= keyword of post() function of requests .

Given that server returns a JSON ( return r.json() ), I can guess that it receives JSON as well. Try to do something like this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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