如何使用Python从RESTful服务获取JSON数据?

85

有没有标准的方法可以使用Python从RESTful服务获取JSON数据?

我需要使用kerberos进行身份验证。

一些代码片段会很有帮助。


这可能会对你有所帮助 https://dev59.com/XXRB5IYBdhLWcg3wH0SW - Sreenath Nannat
2
我不在寻找“基于Python的REST框架”。我想要在Python中使用由某些Java服务器提供的RESTful服务。无论如何,谢谢。 - Bala
5个回答

127

我建议尝试使用requests库。它本质上只是标准库模块(即urllib2、httplib2等)的一个更简单易用的封装。例如,要从需要基本身份验证的URL获取JSON数据,代码如下:

import requests

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

使用Kerberos认证时,requests项目提供了reqests-kerberos库,该库提供了一个Kerberos认证类,您可以与requests一起使用:

import requests
from requests_kerberos import HTTPKerberosAuth

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

5
如果你缺少 requests 模块,只需执行:pip install requests。更多信息和文档请见这里 - benscabbia
为什么我的JSON响应在键值对前面加了u? {u'status': u'FINISHED', u'startTime': u'2016-11-08T15:32:33.241Z', u'jobId': u'f9d71eaa-d439-4a39-a258-54220b14f1b8', u'context': u'sql-context', u'duration': u'0.061 secs'} - KARTHIKEYAN.A

78

如果我没理解错,像这样应该可以工作:

import json
import urllib2
json.load(urllib2.urlopen("url"))

如果不需要通过凭据验证,这将起作用。但是我收到了“urllib2.HTTPError: HTTP Error 401: Unauthorized”错误。 - Bala
1
我需要使用Kerberos身份验证。抱歉,在问题中我忘记提到了。 - Bala
我正在使用Unix系统,尝试使用Kerberos库获取令牌并将其传递给httpConnection.putheader('Authorization', ?)。 - Bala
我不是那个点踩的人,但是乍一看urllib2并不像requests库那么好用。 - Prof. Falken
@AmigableClarkKant 我想提供另一种选择,而不是Mark建议的那个。它似乎符合OP的需求,因为它是被接受的答案,但我同意它可能并不是所有情况下最好的解决方案。 - Trufa
显示剩余4条评论

27

你需要向服务发送HTTP请求,然后解析响应体。我喜欢使用httplib2:

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)

10

如果您想使用Python 3,可以使用以下内容:

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'))

这个程序如何使用Kerberos进行身份验证? - Foon

3

首先,我认为如果你想要实现这个功能,只需要使用urllib2或httplib2就可以了。无论如何,如果你确实需要一个通用的REST客户端,请查看此内容。

https://github.com/scastillo/siesta

然而,我认为该库的功能集对于大多数Web服务来说不适用,因为它们可能会使用oauth等。此外,我不喜欢它是在httplib上编写的,这比httplib2更麻烦,但如果您不必处理大量重定向等问题,则应该可以使用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接