Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python requests POST 400 error

I've been looking to many questions similar to mine but I could not find a solution.

I'm using requests to perform a POST request. I've tried a lot of combinations inside the request but nothing returns a 201 ok.

Here is my code:

 import json
 import requests

 if __name__ == '__main__':

    headers = {'content-type' : 'application/json'}
    url = "http://myserver/ext/v3.1/test_device"
    message = {"atribute_a": "value", "atribute_b": "valueb"}
    params = {"priority":"normal"}

    r = requests.post(url, params=params, headers=headers, data = json.dumps(message) )
    print(r)

I've also tried withou json.dumps but it also gives me 400 bad request. I've also tried to add the params directly to the url like: ...?priority=normal but with no success.

like image 469
lmbcerqueira Avatar asked Apr 11 '17 08:04

lmbcerqueira


People also ask

Why do I get a 400 Bad request error?

The 400 bad request error is an HTTP status code that describes an error caused by an invalid request. Thus, the server can't understand and process it. Most HTTP error 400 bad requests are caused by malformed request syntax, invalid request message framing, or deceptive request routing.

How do I fix error 403 in Python?

If you still get a 403 Forbidden after adding a user-agent , you may need to add more headers, such as referer : headers = { 'User-Agent': '...', 'referer': 'https://...' } The headers can be found in the Network > Headers > Request Headers of the Developer Tools. (Press F12 to toggle it.)

When to return 400 Bad request?

400 Bad Request: The request cannot be fulfilled due to bad syntax. In this case, your client sent you an XML payload that had an invalid zip code, which is a form of invalid syntax; therefore, sending a 400 Bad Request is an appropriate error code to return in this situation.


2 Answers

The easiest technique is to use json instead of data as followed:

requests.post(url, headers=headers, params=params, json=data)
like image 77
marcan2020 Avatar answered Oct 24 '22 12:10

marcan2020


Based on the comments, your server is actually expecting data as a stringified JSON object. As far as the params are concerned, it'd most probably help if they're declared as a tuple of tuples (or a dict of dicts)

Try the following -

headers = {
    'content-type': 'application/json',
}

params = (
    ('priority', 'normal'),
)

data = {
    "atribute_a": "value",
    "atribute_b": false
}

requests.post(url, headers=headers, params=params, data=str(data))
like image 29
Gaurav Ojha Avatar answered Oct 24 '22 14:10

Gaurav Ojha