简体   繁体   中英

Request body has invalid json format - Python

I'm trying to post JSON data (RESTful API) using python.

    null = none
    payload = {
    "priority": 1,
    "hello_id": 207,
    "bye_id": 207,
    "s1": 1,
    "s2": 2,
    "sub": "CHECK 123",
    "t1": "Leave",
    "product_id": null,
    "due": "2001-01-01T06:11:54.884Z",
    "tags": [
    "HelloTag"
    ]
    }

    headers = {'content-type': 'application/json'}
    r = requests.post(myurl, data=json.dumps(payload), headers=headers)
    (OR)
    r = requests.post(myurl, json = json.dumps(payload_post), headers=headers)
    (OR)
    r = requests.post(myurl, data = payload_post, headers=headers, auth=(username_accadmin, password_accadmin))
    (OR)
    r = requests.post(myurl, json=payload, headers=headers)

None of the above 3 lines seems to yield the expected response (or) the response that I get in Postman.

    In the response I get : 
    "Validation failed","errors":[{"field":"priority","message":"Unexpected/invalid field in request","code":"invalid_field"}] 
    (FOR ALL FIELDS IN THE JSON DATA)

Why is the data wrong even when I convert the dict() to JSON using dumps() method?

NOTE : If all the fields in the payload were string, the data is posted as expected.

data should be a dict or list , not a string (which the dumps ) returns.

r = requests.post(myurl, json=payload, headers=headers)

See the documentation . Also, you should use None instead of null in your payload.

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