使用请求和json使其变得简单。调用API
假设API返回一个JSON,使用json.loads函数将JSON对象解析为一个Python目录
通过目录循环提取信息。
请求模块提供有用的功能来循环成功和失败。
if(Response.ok):将帮助确定API调用是否成功(响应代码 - 200)
Response.raise_for_status() 将帮助获取API返回的http代码。
以下是用于进行此类API调用的示例代码。也可以在github中找到。该代码假定API使用摘要式身份验证。可以跳过此选项或使用其他适当的身份验证模块来验证调用该API的客户端。#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()