1

I am supposed to send this:

curl --header "Content-Type: text/plain" --request POST --data "ON" example.com/rest/items/z12

Instead, I am sending this:

import requests
headers = {"Content-Type": "text/plain"}
url = 'http://example.com/rest/items/z12'
_dict = {"ON": ""}
res = requests.post(url, auth=('demo', 'demo'), params=_dict, headers=headers)

And I am getting an Error 400 (Bad Request?)

What am I doing wrong?

2 Answers 2

3

The POST body is set to ON; use the data argument:

import requests

headers = {"Content-Type": "text/plain"}
url = 'http://example.com/rest/items/z12'

res = requests.post(url, auth=('demo', 'demo'), data="ON", headers=headers)

The params argument is used for URL query parameters, and by using a dictionary you asked requests to encode that to a form encoding; so ?ON= is added to the URL.

See the curl manpage:

(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button.

and the requests API:

data – (optional) Dictionary, bytes, or file-like object to send in the body of the Request.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. It worked! I' ve read the manual and in there (docs.python-requests.org/en/latest/user/quickstart/…) it does not specifically mention that I have to use "data" in order to add extra data in the POST body. Also by reading curl man page it says that --data is used to send request parameters. That is why I chose to use params.
@xpanta: right. I'm not sure where curl states that those are parameters; the first sentence in the documentation that I see does mention it is the POST request. Admittedly this does require some knowledge about how HTTP POST normally works. :-)
2

params parameter in the requests.post method is used to add GET parameters to the URL. So you are doing something like this :

curl --header "Content-Type: text/plain" --request POST example.com/rest/items/z12?ON=

You should instead use the data parameter.

import requests
headers = {"Content-Type": "text/plain"}
url = 'http://example.com/rest/items/z12'
res = requests.post(url, auth=('demo', 'demo'), data="ON", headers=headers)

Moreover, if you give a dictionnary to the data parameter, it will send the payload as "application/x-www-form-urlencoded". In your curl command, you send raw string as payload. That's why I changed a bit your example.

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.