<p>使用<a href="http://www.python-requests.org/en/latest/" rel="noreferrer">requests</a>和<a href="https://docs.python.org/2/library/json.html" rel="noreferrer">json</a>使其变得简单。</p>
<ol>
<li>调用API</li>
<li>假设API返回JSON,将JSON对象解析为
Python dict使用<code>json.loads</code>函数</li>
<li>遍历dict以提取信息。</li>
</ol>
<p><a href="http://www.python-requests.org/en/latest/" rel="noreferrer">Requests</a>模块提供有用的函数来循环成功和失败。</p>
<p><code>if(Response.ok)</code>:将帮助您确定您的API调用是否成功(响应代码-200)</p>
<p><code>Response.raise_for_status()</code>将帮助您获取从API返回的http代码。</p>
<p>下面是进行此类API调用的示例代码。也可以在<a href="https://gist.github.com/vinovator/98b0fb7eb30805595bd6" rel="noreferrer">github</a>中找到。代码假设API使用摘要式身份验证。您可以跳过此步骤,也可以使用其他适当的身份验证模块对调用API的客户端进行身份验证。</p>
<pre><code>#Python 2.7.6
#RestfulClient.py
import requests
from requests.auth import HTTPDigestAuth
import json
# Replace with the correct URL
url = "http://api_url"
# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)
# For successful API call, response code will be 200 (OK)
if(myResponse.ok):
# Loading the response data into a dict variable
# json.loads takes in only binary or string variables so using content to fetch binary content
# Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
jData = json.loads(myResponse.content)
print("The response contains {0} properties".format(len(jData)))
print("\n")
for key in jData:
print key + " : " + jData[key]
else:
# If response code is not ok (200), print the resulting http error code with description
myResponse.raise_for_status()
</code></pre>