¿Cómo obtengo datos JSON del servicio RESTful usando Python?


¿Hay alguna forma estándar de obtener datos JSON del servicio RESTful usando Python?

Necesito usar kerberos para la autenticación.

Algún fragmento ayudaría.

Author: Bala, 2011-10-13

5 answers

Algo como esto debería funcionar a menos que me esté perdiendo el punto:

import json
import urllib2
json.load(urllib2.urlopen("url"))
 74
Author: Trufa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-13 08:47:08

Le daría una oportunidad a la biblioteca requests para esto. Esencialmente solo un envoltorio mucho más fácil de usar alrededor de los módulos de biblioteca estándar (es decir, urllib2, httplib2, etc.) se usaría para lo mismo. Por ejemplo, para obtener datos json de una url que requiere autenticación básica se vería así:

import requests

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

Para la autenticación kerberos, el proyecto requests tiene la biblioteca reqests-kerberos que proporciona una clase de autenticación kerberos que puede usar con peticiones :

import requests
from requests_kerberos import HTTPKerberosAuth

response = requests.get('http://thedataishere.com',
                         auth=HTTPKerberosAuth())
data = response.json()
 111
Author: Mark Gemmill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-29 00:35:10

Básicamente necesita hacer una solicitud HTTP al servicio, y luego analizar el cuerpo de la respuesta. Me gusta usar httplib2 para ello:

import httplib2 as http
import json

try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

headers = {
    '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 module
data = json.loads(content)
 25
Author: Christo Buschek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-13 07:53:18

Si desea usar Python 3, puede usar lo siguiente:

import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
    result = json.loads(response.readall().decode('utf-8'))
 7
Author: Andre Wisplinghoff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-11 23:07:36

Bueno en primer lugar creo que el despliegue de su propia solución para esto todo lo que necesita es urllib2 o httplib2 . De todos modos, en caso de que necesite un cliente REST genérico, compruebe esto .

Https://github.com/scastillo/siesta

Sin embargo, creo que el conjunto de características de la biblioteca no funcionará para la mayoría de los servicios web porque probablemente usarán oauth, etc.. . También no me gusta el hecho de que está escrito sobre httplib que es un dolor en comparación con httplib2 todavía debería funcionar si usted no tiene que manejar una gran cantidad de redirecciones, etc ..

 3
Author: dusual,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-13 07:39:14