8

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.

6
  • Isn't there supposed to be a comma between params and headers in requests.post? Commented Apr 11, 2017 at 8:37
  • yes @GauravOjha of course. I tested with a comma. just a bad copy&past Commented Apr 11, 2017 at 8:43
  • Did you try to use data = message directly instead of json.dumps? Commented Apr 11, 2017 at 8:57
  • Yes @GauravOjha. I said that after my code but thanks for trying to help me Commented Apr 11, 2017 at 9:03
  • This probably has to do with how your server is processing this request. Can you show what kind of request is being expected by your server? Commented Apr 11, 2017 at 9:19

2 Answers 2

19

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

requests.post(url, headers=headers, params=params, json=data)
Sign up to request clarification or add additional context in comments.

Comments

9

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.