API:在Python中使用curl调用URL

我正在尝试在python脚本中使用链接缩短服务,但它们的API documentation是JSON(使用curl调用URL)。我是一个初学者,所以我不知道如何实现它。

tiamo520 回答:API:在Python中使用curl调用URL

您可以使用非常流行的名为请求的python库。 Here是带有示例的官方文档。

>>> import requests

>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{u'repository': {u'open_issues': 0,u'url': 'https://github.com/...
,

鉴于提供的文档的第一个示例,您可以像这样简单地使用requests模块:

import requests

data = '{"username":"<Username or email>","password":"<Password>"}' #equal to: -d '{"url":"<Some URL>"}'

response = requests.get('https://www.capsulink.com/api/login',data=data)

其他一切都可以从中构建。

修改

使用requests请求缩短的链接:

import requests

header = {"Api-Key": "<Some API key>"} #equal to: -H 'Api-Key: <Some API key>'

data = '{"url": "<Some URL>"}' #equal to: -d '{"url":"<Some URL>"}'

response = requests.get('https://www.capsulink.com/api/capsulate',headers=header,data=data)

只需将"<Some API key>"替换为所需的API密钥,并将"<Some URL>"替换为您感兴趣的相应URL。

,

您可以使用Python请求模块(https://github.com/psf/requests/)来帮助您进行API查询。实施起来简单,快捷。

>>> r = requests.get('https://api.github.com/user',auth=('user','pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419,u'total_private_repos': 77,...}

在此处参考模块定义:https://requests.kennethreitz.org/en/master/

本文链接:https://www.f2er.com/3167994.html

大家都在问