4

I'm trying to convert the following cURL command into a Request in Python.

curl -H 'customheader: value' -H 'customheader2: value' --data "Username=user&UserPassword=pass" https://thisismyurl

From what I understand, one can GET headers and POST data. So how do I do both like a cURL?

This is what I'm trying:

url = 'myurl'
headers = {'customheader': 'value', 'customheader2': 'value'}
data = 'Username=user&UserPassword=pass'

requests.get(url, headers=headers, data=data)

Which returns: HTTPError: HTTP 405: Method Not Allowed

If I use post: MissingArgumentError: HTTP 400: Bad Request

pppery
  • 3,731
  • 22
  • 33
  • 46
enjoi
  • 274
  • 4
  • 15
  • Do you mean GET with body? Yes, possible. Yes, weird. cf. http://stackoverflow.com/questions/978061/http-get-with-request-body – David Betz Nov 05 '15 at 01:49

1 Answers1

10

When you use the --data command line argument, curl switches to a POST request. Do the same in Python:

requests.post(url, headers=headers, data=data)

From the curl manual:

-d, --data <data>
(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. HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded.

You may want to manually set the Content-Type header accordingly, or use a dictionary for the data parameter (and have requests encode those to the right format for you; the Content-Type header is set for you as well):

url = 'myurl'
headers = {'customheader': 'value', 'customheader2': 'value'}
data = {'Username': 'user', 'UserPassword': 'pass'}

requests.post(url, headers=headers, data=data)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Also, [here](http://docs.python-requests.org/en/latest/) is the document of requests :) – Remi Guan Nov 05 '15 at 02:12
  • As mentioned (Poorly) in my question when I use request.post I receive the 400 Bad Request error. However! When I put the data into a dictionary it worked, so thank-you! – enjoi Nov 05 '15 at 02:51
  • @JavaNoob: that'll be the `Content-Type` header then. You can make your original version work by setting the `Content-Type` header to `application/x-www-form-urlencoded`. – Martijn Pieters Nov 05 '15 at 06:47