xpanta
xpanta

Reputation: 8418

Python: Bad request in POST using requests

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?

Upvotes: 1

Views: 883

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121158

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.

Upvotes: 3

afrancais
afrancais

Reputation: 416

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.

Upvotes: 2

Related Questions