How do I get JSON data from RESTful service using Python? How do I get JSON data from RESTful service using Python? python python

How do I get JSON data from RESTful service using Python?


I would give the requests library a try for this. Essentially just a much easier to use wrapper around the standard library modules (i.e. urllib2, httplib2, etc.) you would use for the same thing. For example, to fetch json data from a url that requires basic authentication would look like this:

import requestsresponse = requests.get('http://thedataishere.com',                         auth=('user', 'password'))data = response.json()

For kerberos authentication the requests project has the reqests-kerberos library which provides a kerberos authentication class that you can use with requests:

import requestsfrom requests_kerberos import HTTPKerberosAuthresponse = requests.get('http://thedataishere.com',                         auth=HTTPKerberosAuth())data = response.json()


Something like this should work unless I'm missing the point:

import jsonimport urllib2json.load(urllib2.urlopen("url"))


You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it:

import httplib2 as httpimport jsontry:    from urlparse import urlparseexcept ImportError:    from urllib.parse import urlparseheaders = {    'Accept': 'application/json',    'Content-Type': 'application/json; charset=UTF-8'}uri = 'http://yourservice.com'path = '/path/to/resource/'target = urlparse(uri+path)method = 'GET'body = ''h = http.Http()# If you need authentication some example:if auth:    h.add_credentials(auth.user, auth.password)response, content = h.request(        target.geturl(),        method,        body,        headers)# assume that content is a json reply# parse content with the json moduledata = json.loads(content)