简介
本全面教程将探讨使用 Python 进行 HTTP API 调用的基本技术。无论你是初学者还是有经验的开发者,都将学习如何高效地与 Web API 进行交互,理解不同的请求方法,并使用 Python 强大的 requests 库处理各种 API 通信场景。
本全面教程将探讨使用 Python 进行 HTTP API 调用的基本技术。无论你是初学者还是有经验的开发者,都将学习如何高效地与 Web API 进行交互,理解不同的请求方法,并使用 Python 强大的 requests 库处理各种 API 通信场景。
HTTP API(应用程序编程接口)是一种通信协议,它允许不同的软件应用程序使用 HTTP 方法通过互联网交换数据。它充当不同系统之间的桥梁,实现无缝的数据传输和交互。
HTTP API 通常使用以下标准方法:
| 方法 | 描述 | 使用场景 |
|---|---|---|
| GET | 获取数据 | 获取用户信息 |
| POST | 创建新资源 | 提交表单数据 |
| PUT | 更新现有资源 | 修改用户资料 |
| DELETE | 删除资源 | 删除记录 |
| PATCH | 部分更新资源 | 更新特定字段 |
HTTP API 请求通常由以下部分组成:
响应包括:
| 代码范围 | 含义 |
|---|---|
| 200 - 299 | 成功响应 |
| 400 - 499 | 客户端错误响应 |
| 500 - 599 | 服务器错误响应 |
大多数 API 需要认证以确保安全访问:
HTTP API 用于各种场景:
在 LabEx,我们建议掌握 HTTP API 技术以构建强大而高效的应用程序。
Requests 库是 Python 中最流行的 HTTP 库,它使 API 交互变得简单直观。它将复杂的 HTTP 操作抽象为简单直接的方法。
## 更新软件包列表
sudo apt update
## 如果尚未安装,则安装 pip
sudo apt install python3-pip
## 安装 Requests 库
pip3 install requests
| 方法 | Requests 函数 | 用途 |
|---|---|---|
| GET | requests.get() | 获取数据 |
| POST | requests.post() | 提交数据 |
| PUT | requests.put() | 更新资源 |
| DELETE | requests.delete() | 删除资源 |
import requests
## 基本 GET 请求
response = requests.get('https://api.example.com/users')
print(response.status_code)
print(response.json())
## 添加查询参数
params = {'page': 1, 'limit': 10}
response = requests.get('https://api.example.com/users', params=params)
## 发送 JSON 数据
data = {'username': 'john_doe', 'email': 'john@example.com'}
response = requests.post('https://api.example.com/users', json=data)
## API 密钥认证
headers = {'Authorization': 'Bearer YOUR_API_KEY'}
response = requests.get('https://api.example.com/data', headers=headers)
## 基本认证
response = requests.get('https://api.example.com/data',
auth=('username', 'password'))
try:
response = requests.get('https://api.example.com/data')
response.raise_for_status() ## 对 4xx/5xx 状态码引发异常
except requests.exceptions.RequestException as e:
print(f"发生错误:{e}")
## 超时和自定义设置
response = requests.get('https://api.example.com/data',
timeout=5, ## 5 秒超时
verify=False) ## 禁用 SSL 验证
| 属性 | 描述 |
|---|---|
| status_code | HTTP 状态码 |
| text | 作为字符串的响应内容 |
| json() | 解析 JSON 响应 |
| headers | 响应头 |
在 LabEx,我们强调掌握 Requests 库以在 Python 中进行高效的 API 交互。
def fetch_all_data(base_url):
page = 1
all_data = []
while True:
response = requests.get(f'{base_url}?page={page}')
data = response.json()
if not data:
break
all_data.extend(data)
page += 1
return all_data
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def create_retry_session(retries=3):
session = requests.Session()
retry_strategy = Retry(
total=retries,
status_forcelist=[429, 500, 502, 503, 504],
method_whitelist=["HEAD", "GET", "OPTIONS"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)
session.mount("http://", adapter)
return session
import concurrent.futures
import requests
def fetch_url(url):
response = requests.get(url)
return response.json()
def concurrent_api_calls(urls):
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(fetch_url, urls))
return results
import time
import requests
class RateLimitedAPI:
def __init__(self, calls_per_minute):
self.calls_per_minute = calls_per_minute
self.interval = 60 / calls_per_minute
def call_api(self, url):
time.sleep(self.interval)
return requests.get(url)
| 策略 | 描述 | 使用场景 |
|---|---|---|
| API 密钥 | 基于简单令牌 | 公共 API |
| OAuth | 安全的委托访问 | 复杂的认证流程 |
| JWT | 无状态认证 | 微服务 |
def robust_api_call(url, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt)
import requests
import functools
@functools.lru_cache(maxsize=100)
def cached_api_call(url):
response = requests.get(url)
return response.json()
在 LabEx,我们建议掌握这些高级 API 调用技术,以构建强大而高效的 Python 应用程序。
通过掌握 Python 中的 HTTP API 调用,开发者能够无缝集成外部服务,从 Web API 中检索数据,并构建强大的应用程序。本教程借助 Python 通用的编程能力,为你提供了进行 GET、POST 及其他 HTTP 请求、管理认证以及有效处理 API 响应的关键技能。