Python调用REST API接口的几种方式汇总

作者:py3study 时间:2023-01-06 16:42:17 

相信做过自动化运维的同学都用过REST API接口来完成某些动作。API是一套成熟系统所必需的接口,可以被其他系统或脚本来调用,这也是自动化运维的必修课。

本文主要介绍python中调用REST API的几种方式,下面是python中会用到的库。

  • - urllib2

  • - httplib2

  • - pycurl

  • - requests

urllib2

- Sample1


import urllib2, urllib
github_url = 'https://api.github.com/user/repos'
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, github_url, 'user', '***')
auth = urllib2.HTTPBasicAuthHandler(password_manager) # create an authentication handler
opener = urllib2.build_opener(auth) # create an opener with the authentication handler
urllib2.install_opener(opener) # install the opener...
request = urllib2.Request(github_url, urllib.urlencode({'name':'Test repo', 'description': 'Some test repository'})) # Manual encoding required
handler = urllib2.urlopen(request)
print handler.read()

- Sample2


import urllib2
url = 'http://ems.vip.ebay.com/removeSIforcloud.cgi?ip=' + ip
req = urllib2.Request(url)
req.add_header('IAF',abc.token_authiaas)
try:
 resp = urllib2.urlopen(req)
except urllib2.HTTPError, error:
 print "Cannot remove service instance!", error
 sys.exit(1)
response = resp.read()
print response

- Sample3


import urllib2, urllib, base64
url = "https://reparo.stratus.ebay.com/reparo/bootstrap/registerasset/" + rackid + "/" + asset
data = urllib.urlencode({
       'reservedResource':'RR-Hadoop',
       'resourceCapability':'Production',
       'movetoironic':'False',
       'output':'json'
   })
print "Bootstrap Asset jobs starting .............."

base64string = base64.encodestring('%s:%s' % (user, passwd)).replace('\n', '')
request = urllib2.Request(url, data, headers={"Authorization" : "Basic %s" % base64string})
response = urllib2.urlopen(request).read()
response_json = json.loads(response)
response_status = response_json['status']
status_code = response_status['statusCode']
status = response_status['status']
message = response_status['message']      
print status_code , status, message

2. httplib2


import urllib, httplib2
github_url = '
h = httplib2.Http(".cache")
h.add_credentials("user", "******", "
data = urllib.urlencode({"name":"test"})
resp, content = h.request(github_url, "POST", data)
print content

3. pycurl


import pycurl, json
github_url = "
user_pwd = "user:*****"
data = json.dumps({"name": "test_repo", "description": "Some test repo"})
c = pycurl.Curl()
c.setopt(pycurl.URL, github_url)
c.setopt(pycurl.USERPWD, user_pwd)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.perform()

4. requests


import requests, json
github_url = "
data = json.dumps({'name':'test', 'description':'some test repo'})
r = requests.post(github_url, data, auth=('user', '*****'))
print r.json

以上几种方式都可以调用API来执行动作,但requests这种方式代码最简洁,最清晰,建议采用。

来源:https://cloud.tencent.com/developer/article/1565221

标签:Python,调用,REST,API,接口
0
投稿

猜你喜欢

  • SESSION存放在数据库用法实例

    2024-05-11 10:09:56
  • python使用socket向客户端发送数据的方法

    2023-08-13 00:16:51
  • Python中getattr函数和hasattr函数作用详解

    2022-10-29 15:42:11
  • python实现使用遗传算法进行图片拟合

    2022-05-25 03:31:53
  • Vue2.0/3.0双向数据绑定的实现原理详解

    2024-05-21 10:17:58
  • Python3.7基于hashlib和Crypto实现加签验签功能(实例代码)

    2023-03-25 16:23:00
  • PyCharm最新激活码PyCharm2020.2.3有效

    2023-05-14 21:18:55
  • 提高javascript的速度系列(序)

    2008-07-15 12:38:00
  • 初窥交互设计

    2009-10-10 10:52:00
  • Python实现替换文件中指定内容的方法

    2023-02-23 06:26:03
  • python实现自动化上线脚本的示例

    2021-02-01 05:14:49
  • Numpy中创建数组的9种方式小结

    2021-03-25 21:39:43
  • 利用FrontPage 2003制作网络申请系统

    2008-02-21 14:34:00
  • Go语言服务器开发之客户端向服务器发送数据并接收返回数据的方法

    2024-04-27 15:39:58
  • 在keras里面实现计算f1-score的代码

    2021-12-13 08:39:43
  • 详解Python开发语言中的基本数据类型

    2022-12-11 20:13:35
  • MySQL Daemon failed to start错误解决办法

    2024-01-16 23:22:21
  • 原生javascript运动函数的封装示例【匀速、抛物线、多属性的运动等】

    2024-04-25 13:15:33
  • python脚本定时发送邮件

    2023-08-07 16:36:02
  • Ubuntu下完美实现迁移MySQL数据库位置

    2024-01-16 15:39:26
  • asp之家 网络编程 m.aspxhome.com