Reputation: 284
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
Upvotes: 5
Views: 9688
Reputation: 1121216
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)
Upvotes: 11