如何使用Python从RESTful服务获取JSON数据?
有没有使用Python从RESTful服务获取JSON数据的标准方法?
我需要使用kerberos进行身份验证。
一些片段会有所帮助。
5个解决方案
111 votes
我会试试请求库。 基本上只是一个更容易使用的标准库模块(即urllib2,httplib2等)的包装器,你可以使用相同的东西。 例如,从需要基本身份验证的URL获取json数据将如下所示:
import requests
response = requests.get('http://thedataishere.com',
auth=('user', 'password'))
data = response.json()
对于kerberos身份验证,请求项目具有reqests-kerberos库,该库提供可用于请求的kerberos身份验证类:
import requests
from requests_kerberos import HTTPKerberosAuth
response = requests.get('http://thedataishere.com',
auth=HTTPKerberosAuth())
data = response.json()
Mark Gemmill answered 2019-04-21T01:13:30Z
75 votes
除非我忽略了这一点,否则这样的事情应该有效:
import json
import urllib2
json.load(urllib2.urlopen("url"))
Trufa answered 2019-04-21T01:12:58Z
25 votes
您基本上需要向服务发出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)
Christo Buschek answered 2019-04-21T01:13:54Z
7 votes
如果您希望使用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'))
Andre Wisplinghoff answered 2019-04-21T01:14:19Z
3 votes
首先,我认为为此您推出自己的解决方案就是urllib2或httplib2。 无论如何,如果您确实需要通用REST客户端,请检查这一点。
[https://github.com/scastillo/siesta]
但是我认为库的功能集对大多数Web服务都不起作用,因为它们可能会使用oauth等。 此外,我不喜欢它写在httplib上的事实,这是一个痛苦,与httplib2相比,如果你不需要处理大量的重定向等仍然适用于你。
dusual answered 2019-04-21T01:14:57Z