2

I wanted to query Freebase API to get the list of teams José Mourinho has played for.

So, the URL i used on my browser is

https://www.googleapis.com/freebase/v1/mqlread?query=[{"name": "José Mourinho","/sports/pro_athlete/teams": [{"mid": null,"team": null,"to": null,"optional": true}]}]

However,

import json
import urllib

service_url="https://www.googleapis.com/freebase/v1/mqlread"
query = '[{"name": "' + "José Mourinho" + '","/sports/pro_athlete/teams": [{"mid": null,"team": null,"to": null,"optional": true}]}]'
url = service_url + '?' + 'query='+query
response = json.loads(urllib.urlopen(url).read())

Gives me an error saying,

UnicodeError: URL u'https://www.googleapis.com/freebase/v1/mqlread?query=[{"name": "Jos\xe9 Mourinho","/sports/pro_athlete/teams": [{"mid": null,"team": null,"to": null,"optional": true}]}]' contains non-ASCII characters

What is the solution to this?

John Oliver
  • 97
  • 1
  • 2
  • 6

1 Answers1

1

I think you skipped over a little bit of the docs. Try this instead:

# coding=UTF-8

import json
import urllib

service_url = "https://www.googleapis.com/freebase/v1/mqlread"
query = [{
    '/sports/pro_athlete/teams': [
        {
            'to': None,
            'optional': True,
            'mid': None,
            'team': None
        }
    ],
    'name': 'José Mourinho'
}]

url = service_url + '?' + urllib.urlencode({'query': json.dumps(query)})
response = json.loads(urllib.urlopen(url).read())

print response

Rather than building the query string yourself, use json.dumps and urllib.urlencode to create it for you. They're good at this.

Note: if you can use the requests package, that last bit could be:

import requests
response = requests.get(service_url, params={'query': json.dumps(query)})

Then you get to skip the URL construction and escaping altogether!

Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65