user330612
user330612

Reputation: 2239

python requests module doesnt work when curl works. What am I doing wrong?

I have a curl request and a similar request using python requests module to a local web service. While the curl request is working correctly, the request made via python isnt working as expected, ie doesn't return a json reponse.

Any ideas as why this is happening? With python I still get a 200 response, but getting HTML response text instead of json like in curl and the response is something about invalid session etc.

This is the curl request

root@weve1:~$ curl -k --GET --data "ajax=getPermissions&project=test&session.id=5604d7ce-f3dd-4349-8957-563c2675ae5c" http://localhost:12320/manager
{
  "permissions" : [ {
    "permission" : [ "ADMIN" ],
    "username" : "azkaban"
  } ],
  "project" : "test",
  "projectId" : 92
}

This is the same request made in python

root@weve1:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> s=requests.get('http://localhost:12320/manager',data={'ajax':'getPermissions','project':'test','session.id':'5604d7ce-f3dd-4349-8957-563c2675ae5c'})
>>> s.json()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/requests/models.py", line 741, in json
    return json.loads(self.text, **kwargs)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>> 

Upvotes: 1

Views: 2766

Answers (1)

poke
poke

Reputation: 387507

From the curl man page:

-G/--get

When used, this option will make all data specified with -d/--data or --data-binary to be used in a HTTP GET request instead of the POST request that otherwise would be used. The data will be appended to the URL with a '?' separator.

So curl is actually passing the parameters as a query string instead, i.e. http://localhost:12320/manager?ajax=getPermissions&project=test&session.id=5604d7ce-f3dd-4349-8957-563c2675ae5c.

In order to pass data in the URL with requests, you need to pass the data in the params argument:

data = { 'ajax': 'getPermissions', 'project': 'test', 'session.id': '5604d7ce-f3dd-4349-8957-563c2675ae5c' }
s = requests.get('http://localhost:12320/manager', params=data)

The data argument only refers to the actual request body.

Upvotes: 4

Related Questions