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.
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.
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.)
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.
The easiest technique is to use json
instead of data
as followed:
requests.post(url, headers=headers, params=params, json=data)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With