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


Posted in Python onOctober 19, 2020

相信做过自动化运维的同学都用过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这种方式代码最简洁,最清晰,建议采用。

以上就是Python调用REST API接口的几种方式汇总的详细内容,更多关于Python调用REST API接口的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python中easy_install 和 pip 的安装及使用
Jun 05 Python
Python使用PIL模块生成随机验证码
Nov 21 Python
Python基于PyGraphics包实现图片截取功能的方法
Dec 21 Python
在Mac上删除自己安装的Python方法
Oct 29 Python
python爬取cnvd漏洞库信息的实例
Feb 14 Python
Python基础之函数的定义与使用示例
Mar 23 Python
Python paramiko模块使用解析(实现ssh)
Aug 30 Python
Python 中 -m 的典型用法、原理解析与发展演变
Nov 11 Python
pyinstaller还原python代码过程图解
Jan 08 Python
Django中FilePathField字段的用法
May 21 Python
flask开启多线程的具体方法
Aug 02 Python
对Pytorch 中的contiguous理解说明
Mar 03 Python
Python爬虫抓取论坛关键字过程解析
Oct 19 #Python
python MD5加密的示例
Oct 19 #Python
python Yaml、Json、Dict之间的转化
Oct 19 #Python
Python pip 常用命令汇总
Oct 19 #Python
Python环境使用OpenCV检测人脸实现教程
Oct 19 #Python
python Tornado框架的使用示例
Oct 19 #Python
python mock测试的示例
Oct 19 #Python
You might like
PHP.MVC的模板标签系统(四)
2006/09/05 PHP
php类的扩展和继承用法实例
2015/06/20 PHP
PHP使用内置函数file_put_contents写入文件及追加内容的方法
2015/12/07 PHP
反射调用private方法实践(php、java)
2015/12/21 PHP
php中curl和soap方式请求服务超时问题的解决
2018/06/11 PHP
javascript getElementsByName()的用法说明
2009/07/31 Javascript
判断用户是否在线的代码
2011/03/05 Javascript
JQuery入门—编写一个简单的JQuery应用案例
2013/01/03 Javascript
利用js制作html table分页示例(js实现分页)
2014/04/25 Javascript
函数式 JavaScript(一)简介
2014/07/07 Javascript
JavaScript中用let语句声明作用域的用法讲解
2016/05/20 Javascript
解决vue router使用 history 模式刷新后404问题
2017/07/19 Javascript
XMLHttpRequest对象_Ajax异步请求重点(推荐)
2017/09/28 Javascript
iconfont的三种使用方式详解
2018/08/05 Javascript
JS 实现获取验证码 倒计时功能
2018/10/29 Javascript
Python中元组,列表,字典的区别
2017/05/21 Python
Python 用Redis简单实现分布式爬虫的方法
2017/11/23 Python
tensorflow中next_batch的具体使用
2018/02/02 Python
深入理解Python 关于supper 的 用法和原理
2018/02/28 Python
解决项目pycharm能运行,在终端却无法运行的问题
2019/01/19 Python
Python常见的pandas用法demo示例
2019/03/16 Python
超简单使用Python换脸实例
2019/03/27 Python
Python openpyxl 插入折线图实例
2020/04/17 Python
Python新手学习raise用法
2020/06/03 Python
澳大利亚冲浪和时尚服装网上购物:SurfStitch
2017/07/29 全球购物
北美三大旅游网站之一:Travelocity
2017/08/12 全球购物
英国Flybe航空官网:欧洲最大的独立支线廉价航空公司
2019/07/15 全球购物
英国领先的男装设计师服装独立零售商:Repertoire Fashion
2020/10/19 全球购物
送温暖献爱心活动总结
2014/07/08 职场文书
个性发展自我评价2015
2015/03/09 职场文书
成绩单家长意见
2015/06/03 职场文书
导游词范文之颐和园/重庆/云台山
2019/09/10 职场文书
详解Redis瘦身指南
2021/05/26 Redis
SpringCloud的JPA连接PostgreSql的教程
2021/06/26 Java/Android
SQL Server的存储过程与触发器以及系统函数和自定义函数
2022/04/10 SQL Server
使用pd.merge表连接出现多余行的问题解决
2022/06/16 Python