Pass a JSON object to an url with requests

2024/9/21 5:39:53

So, I want to use Kenneth' excellent requests module. Stumbled up this problem while trying to use the Freebase API.

Basically, their API looks like that:

https://www.googleapis.com/freebase/v1/mqlread?query=...

as a query, they expect a JSON object, here's one that will return a list of wines with their country and percentage of alcohol:

[{"country":       null,"name":          null,"percentage_alcohol": null,"percentage_alcohol>": 0,"type":          "/food/wine"
}]​

Of course, we'll have to escape the hell out of this before passing it to an URL, so the actual query will look like this:

 fullurl = 'https://www.googleapis.com/freebase/v1/mqlread?query=%5B%7B%22percentage_alcohol%3E%22%3A+0%2C+%22country%22%3A+null%2C+%22type%22%3A+%22%2Ffood%2Fwine%22%2C+%22name%22%3A+null%2C+%22percentage_alcohol%22%3A+null%7D%5D'

Now,

r = requests.get(fullurl)
print r.status_code
>>> 400

because the site claims it couldn't parse the query.

r2 = urllib2.urlopen(fullurl)
print r2.getcode()
>>> 200

No problem here, I get a proper return. Interestingly,

# This is the url of our requests.get request
print urllib2.urlopen(r.url).getcode() 
>>> 200

Why? Am I using the module wrong? Or is it a bug in requests?

Answer

It works for me. Here's what I did:

>>> params = [{"country": None,
...            "name": None,
...            "percentage_alcohol": None,
...            "percentage_alcohol>": 0,
...            "type": "/food/wine"
...          }]
>>> import json
>>> params_json = json.dumps(params)>>> import requests
>>> url = "https://www.googleapis.com/freebase/v1/mqlread?query=%s"
>>> r = requests.get(url % params_json)
>>> r.status_code
200>>> content_json = json.loads(r.content)
>>> import pprint
>>> pprint.pprint(content_json)
{u'result': [{u'country': u'New Zealand',u'name': u'2003 Cloudy Bay Sauvignon Blanc',u'percentage_alcohol': 13.5,u'type': u'/food/wine'},{u'country': u'France',u'name': u'G.H. Mumm Cordon Rouge Brut',u'percentage_alcohol': 12.0,u'type': u'/food/wine'},
....

I cut the rest off for brevity. There are 100 results. requests.__version__ == '0.10.6'

https://en.xdnf.cn/q/72264.html

Related Q&A

jenkinsapi python - how to trigger and track the job result

I am using JenkinsAPI to trigger parametrized jobs. I am aware of the REST API that Jenkins use, but our setup does not allow that directly; so the main mean for me to trigger jobs is through this libr…

Django test parallel AppRegistryNotReady

I am trying to understand how to run django tests in parallel with in memory sqlite3.I have django app with that structure:gbookorder...tests__init__.pytest_a1.pytest_b1.pyutils.pytest_a1.py and test_b…

ImportError: PyCapsule_Import could not import module pyexpat

I am using Jenkins to build a python (Flask) solution to deploy to Google App Engine. As part of the build process I run a few integration tests. One of them is failing with the following error. ERROR:…

Python - Get max value in a list of dict

I have a dataset with this structure :In[17]: allIndices Out[17]: [{0: 0, 1: 1.4589, 4: 2.4879}, {0: 1.4589, 1: 0, 2: 2.1547}, {1: 2.1547, 2: 0, 3: 4.2114}, {2: 4.2114, 3: 0}, {0: 2.4879, 4: 0}]Id lik…

Rescaling axis in Matplotlib imshow under unique function call

I have written a function module that takes the argument of two variables. To plot, I hadx, y = pylab.ogrid[0.3:0.9:0.1, 0.:3.5:.5] z = np.zeros(shape=(np.shape(x)[0], np.shape(y)[1]))for i in range(le…

f2py array valued functions

Do recent versions of f2py support wrapping array-valued fortran functions? In some ancient documentation this wasnt supported. How about it now?Lets for example save the following function as func.f…

Unique strings in a pandas dataframe

I have following sample DataFrame d consisting of two columns col1 and col2. I would like to find the list of unique names for the whole DataFrame d. d = {col1:[Pat, Joseph, Tony, Hoffman, Miriam, Good…

finding index of multiple items in a list

I have a list myList = ["what is your name", "Hi, how are you","What about you", "How about a coffee", "How are you"]Now I want to search index of all …

Debugging asyncio code in PyCharm causes absolutely crazy unrepeatable errors

In my project that based on asyncio and asyncio tcp connections that debugs with PyCharm debugger I got very and very very absurd errors.If I put breakpoint on code after running, the breakpoint never …

how to generate pie chart using dict_values in Python 3.4?

I wanted the frequency of numbers in a list which I got using Counter library. Also, I got the keys and values using keys = Counter(list).keys() and values = Counter(list).values() respectively, where …