python使用restful_如何使用python向RESTfulAPI发出请求?

使用请求和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()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值