一、Python 可以使用 requests 库来调用 API 接口获取数据。以下是基本的步骤:
1.安装 requests 库
pip install requests
2.导入 requests 库
import requests
3.构建 API 请求的 URL
根据 API 文档,构建请求的URL。
例如, https://api.example.com/posts
是获取所有帖子的 URL。
4.发送 API 请求
使用 requests.get()
方法发送请求,并接收响应。
response = requests.get(url)
- 处理响应数据
响应的数据格式可能有多种,如 JSON、XML 等。
如果响应数据是 JSON 格式的,可以将其转换为 Python 字典并进行处理。
data = response.json()
完整的代码示例:
import requests
url = "https://api.example.com/posts"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
# 对响