ashim
ashim

Reputation: 25560

Difference between linux curl and python requests, why GET request has different result?

Why next two methods of obtaining authentication token are not equivalent? First one is using curl in terminal:

curl -X POST "http://myurl.com" -d "grant_type=password&username=me&password=mypass&client_secret=123&client_id=456"

This request successfully returns the token. If I use requests library for python:

import requests   
url = 'http://myurl.com'                                                              

query_args = { "grant_type":"password",
               "username":'me',
               "password":'mypass',
               "client_secret":'123',
               'client_id':'456'}
r = requests.get(url, data=query_args)

the result I get is r.status_code is 404, so I cannot get the token. Why the first method works and the second does not?

Also, how to make the second approach work?

Thank you!

Upvotes: 0

Views: 879

Answers (1)

ModulusJoe
ModulusJoe

Reputation: 1446

So the curl -d flag send data as post data, from the man page:

   -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. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F/--form.

So you should be using request.post. You will also possibly want to use the params attribute not the data one, see the following example:

>>> data = {'test':'12345'}
>>> url = 'http://myurl.com'
>>> r = requests.post(url,params=data)
>>> print r.url
http://myurl.com/?test=12345
>>> r = requests.post(url,data=data)
>>> print r.url
http://myurl.com/
>>> 

Upvotes: 1

Related Questions