本教程将向您介绍Web API,并教您如何使用请求Python库来获取和更新Web API中的信息。 您还将作为工作示例学习如何与Twitter API进行交互。
Web API简介
API(应用程序编程接口)是用于构建可被各种客户端使用的HTTP服务的框架。 Web API使用HTTP协议来处理客户端和Web服务器之间的请求。
使开发人员能够集成和使用其基础架构的一些最常见的API包括:
- Google API
- Twitter API
- 亚马逊API
- Facebook API
与其他静态数据源相比,使用API的最重要原因之一是因为它是实时的。 例如,我们将要使用的Twitter API将从社交网络获取实时数据。
另一个优点是数据一直在变化,因此,如果您要定期下载数据,那将很耗时。
使用请求库
为了使用API,您将需要安装请求Python库。 Requests是Python中的HTTP库,使您可以使用Python发送HTTP请求。
安装要求
在您的终端中,键入:
pip install requests
要检查安装是否成功,请在您的Python解释器或终端中发出以下命令:
import requests
如果没有错误,则说明安装成功。
如何从Web API获取信息
GET方法用于从Web服务器获取信息。 让我们看看如何发出GET请求以获取GitHub的公共时间表。
我们使用变量req
来存储来自请求的响应。
import requests
req = requests.get('https://github.com/timeline.json')
现在,我们已经向GitHub时间轴发出了请求,让我们获取响应中包含的编码和内容。
import requests
req = requests.get('https://github.com/timeline.json')
req.text
u'{"message":"Hello there, wayfaring stranger. If you\u2019re reading this then you probably didn\u2019t see our blog post a couple of years back announcing that this API would go away: https://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}
import requests
req = requests.get('https://github.com/timeline.json')
req.encoding
'utf-8'
请求具有内置的JSON解码,可用于获取JSON格式的请求的响应。
import requests
import json
req = requests.get('https://github.com/timeline.json')
req.json()
{u'documentation_url': u'https://developer.github.com/