答案:Python调用REST API最核心的工具是requests库,它简化了HTTP请求的发送与响应处理。首先通过pip install requests安装库,然后使用requests.get()或requests.post()等方法发送请求,并可通过response.json()解析JSON数据。为确保程序健壮,需添加异常处理,捕获ConnectionError、Timeout、HTTPError等异常,并使用response.raise_for_status()检查状态码。认证方式包括基本认证(HTTPBasicAuth)、API Key(作为参数或请求头)、Bearer Token(Authorization头)以及OAuth 2.0(常借助requests-oauthlib)。错误处理应覆盖网络层、HTTP响应层和业务逻辑层,如解析JSON时捕获ValueError,检查API返回的错误字段。对于临时故障,可结合Retry机制实现自动重试。参数管理方面,查询字符串用params传递,JSON请求体用json参数,表单数据用data,文件上传用files,请求头通过headers设置。始终依据API文档确定数据格式和认证方式,确保请求正确。

在Python中调用REST API,最核心、最便捷的工具无疑是
requests
要用Python调用REST API,你需要做的主要就是安装并使用
requests
首先,确保你已经安装了
requests
pip install requests
然后,你可以这样来发送不同类型的请求:
立即学习“Python免费学习笔记(深入)”;
1. 发送GET请求 这是最常见的请求类型,用于从服务器获取数据。
import requests
try:
response = requests.get('https://api.example.com/data')
response.raise_for_status() # 如果状态码不是200,则抛出HTTPError异常
data = response.json() # 尝试将响应解析为JSON
print("获取到的数据:", data)
except requests.exceptions.HTTPError as errh:
print(f"HTTP错误: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"连接错误: {errc}")
except requests.exceptions.Timeout as errt:
print(f"超时错误: {errt}")
except requests.exceptions.RequestException as err:
print(f"其他错误: {err}")
except ValueError: # 如果response.json()失败,说明响应不是有效的JSON
print("响应不是有效的JSON格式。")
print("原始响应文本:", response.text)这里我直接加入了错误处理,因为实际开发中,没有错误处理的API调用几乎是不可想象的。
response.raise_for_status()
2. 发送POST请求 POST请求通常用于向服务器提交数据,比如创建新资源。
import requests
import json
url = 'https://api.example.com/items'
headers = {'Content-Type': 'application/json'} # 告诉服务器我们发送的是JSON数据
payload = {
'name': '新商品',
'price': 99.99,
'description': '这是一个通过API创建的新商品。'
}
try:
response = requests.post(url, headers=headers, json=payload) # 使用json参数,requests会自动序列化字典并设置Content-Type
response.raise_for_status()
created_item = response.json()
print("创建成功,响应:", created_item)
except requests.exceptions.RequestException as e:
print(f"POST请求失败: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f"服务器响应内容: {e.response.text}")
except ValueError:
print("响应不是有效的JSON格式。")
print("原始响应文本:", response.text)注意这里我用了
json=payload
requests
Content-Type
data=payload
3. 添加请求头(Headers) 请求头用于传递额外的信息,比如认证令牌、内容类型等。
import requests
url = 'https://api.example.com/protected_resource'
# 假设你需要一个API Key或者Bearer Token进行认证
headers = {
'Authorization': 'Bearer your_access_token_here',
'User-Agent': 'MyPythonApp/1.0', # 自定义User-Agent是个好习惯
'Accept': 'application/json' # 告诉服务器我们期望JSON格式的响应
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
print("成功获取受保护资源:", response.json())
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f"服务器响应内容: {e.response.text}")这些就是Python调用REST API的基本骨架。实际操作中,你还会遇到认证、错误处理、参数管理等更具体的问题。
在调用REST API时,认证和授权是绕不开的话题,毕竟大多数有价值的服务都不会让你“裸奔”访问。我个人觉得,这部分往往比发送请求本身更让人头疼,因为不同的API提供方有不同的实现方式。
1. 基本认证(Basic Authentication) 这是最简单的一种,用户名和密码以Base64编码的形式放在HTTP请求头中。
requests
import requests
from requests.auth import HTTPBasicAuth
url = 'https://api.example.com/basic_auth_resource'
response = requests.get(url, auth=HTTPBasicAuth('your_username', 'your_password'))
# 或者更简洁地
# response = requests.get(url, auth=('your_username', 'your_password'))
response.raise_for_status()
print("基本认证成功:", response.json())虽然方便,但安全性相对较低,不推荐在敏感场景下使用,尤其是在不安全的网络环境下。
2. API Key认证 很多API会给你一个API Key,它可能是:
https://api.example.com/data?api_key=YOUR_API_KEY
params = {'api_key': 'YOUR_API_KEY'}
response = requests.get('https://api.example.com/data', params=params)X-API-Key: YOUR_API_KEY
Authorization: Api-Key YOUR_API_KEY
headers = {'X-API-Key': 'YOUR_API_KEY'}
response = requests.get('https://api.example.com/data', headers=headers)具体是哪种,得看API文档,这是金科玉律。
3. 令牌认证(Token Authentication,如Bearer Token) 这是目前最流行的方式之一,尤其是在OAuth 2.0流程中。你通过某种方式(比如登录)获取一个令牌(token),然后每次请求都将这个令牌放在
Authorization
Bearer YOUR_TOKEN
token = 'your_very_long_and_secret_access_token'
headers = {
'Authorization': f'Bearer {token}'
}
response = requests.get('https://api.example.com/protected_data', headers=headers)
response.raise_for_status()
print("令牌认证成功:", response.json())我个人觉得这种方式既灵活又相对安全,因为令牌通常有过期时间,而且可以被撤销。管理好令牌的生命周期(刷新、存储)是这里的关键。
4. OAuth 2.0 OAuth 2.0本身是一个授权框架,而不是简单的认证机制。它涉及多个步骤(如获取授权码、交换访问令牌、刷新令牌等)。
requests
requests-oauthlib
总结来说,处理认证授权的核心在于:仔细阅读API文档。它会告诉你期望哪种认证方式、令牌如何获取、如何刷新。我见过太多因为认证头格式不对或者令牌过期而导致API调用失败的案例了。
错误处理是构建健壮应用程序的基石。如果你的API调用没有适当的错误处理,一旦网络波动、API服务宕机或数据格式不符,程序就可能崩溃。我通常会把错误处理分为几个层面:网络层、HTTP响应层和业务逻辑层。
1. 网络层错误 这些错误发生在HTTP请求甚至还没到达服务器的时候,比如DNS解析失败、网络连接中断、请求超时等。
requests
requests.exceptions
requests.exceptions.ConnectionError
requests.exceptions.Timeout
requests.exceptions.RequestException
requests
requests
import requests
try:
response = requests.get('http://nonexistent-domain-12345.com', timeout=5) # 故意制造连接错误和超时
response.raise_for_status()
print(response.json())
except requests.exceptions.ConnectionError as e:
print(f"网络连接失败或DNS解析错误: {e}")
except requests.exceptions.Timeout as e:
print(f"请求超时: {e}")
except requests.exceptions.RequestException as e:
print(f"发生其他requests错误: {e}")
except Exception as e: # 捕获其他非requests库的异常
print(f"发生未知错误: {e}")我喜欢把
requests.exceptions.RequestException
requests
ConnectionError
Timeout
2. HTTP响应层错误 即使请求成功发送并到达服务器,服务器也可能返回非2xx(成功)的状态码,表示请求处理失败。
response.status_code
response.raise_for_status()
requests
requests.exceptions.HTTPError
import requests
try:
response = requests.get('https://httpbin.org/status/404')
response.raise_for_status() # 这会在这里抛出HTTPError
print(response.json())except requests.exceptions.HTTPError as e: print(f"HTTP错误: {e}") print(f"状态码: {e.response.status_code}") print(f"响应内容: {e.response.text}") # 打印服务器返回的错误信息 except requests.exceptions.RequestException as e: print(f"发生其他requests错误: {e}")
我发现`raise_for_status()`真的能省很多事,它把检查状态码的重复劳动自动化了。在`HTTPError`中,`e.response`属性可以让你访问原始的响应对象,从而获取状态码和具体的错误信息。
**3. 业务逻辑层错误和数据解析错误**
即使HTTP状态码是200 OK,API返回的数据也可能不符合预期,或者不是有效的JSON。
* **`response.json()`解析失败**: 如果API返回的不是JSON,或者JSON格式有误,调用`response.json()`会抛出`json.JSONDecodeError`(Python 3.5+)或`ValueError`(旧版本Python)。
```python
import requests
import json
try:
# 模拟一个返回非JSON内容的成功响应
response = requests.get('https://httpbin.org/html')
response.raise_for_status()
data = response.json() # 这里会抛出ValueError或json.JSONDecodeError
print(data)
except (json.JSONDecodeError, ValueError) as e:
print(f"JSON解析错误: {e}")
print(f"原始响应文本: {response.text[:200]}...") # 打印部分原始响应,帮助调试
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")"error"
# 假设API返回 { "status": "error", "message": "无效的参数" }
response_data = {"status": "error", "message": "无效的参数"}
if response_data.get("status") == "error":
print(f"API业务错误: {response_data.get('message')}")这部分就需要根据具体的API文档来定制了。我通常会封装一个函数来处理这些,比如检查
data.get('code')data.get('errorMessage')4. 重试机制 对于一些临时的网络问题或服务器负载高导致的5xx错误,简单的重试可能会解决问题。你可以手动实现简单的重试逻辑,或者使用像
requests-retry
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# 简单的重试策略
def requests_retry_session(
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 503, 504),
session=None,
):
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
# 使用重试会话
try:
session = requests_retry_session()
# 模拟一个偶尔失败的API
response = session.get('https://httpbin.org/status/500') # 第一次可能失败,重试
response.raise_for_status()
print("重试后成功获取:", response.text)
except requests.exceptions.RequestException as e:
print(f"请求最终失败(含重试): {e}")我个人觉得,对于生产环境的API调用,引入重试机制是很有必要的,它能显著提高程序的健壮性和容错性。
管理好请求参数是确保API调用正确响应的关键,这就像给一个黑盒子输入正确的指令。不同的HTTP方法和API设计会要求你以不同的方式传递数据。
1. 查询字符串参数(Query Parameters) 主要用于GET请求,通常出现在URL的
?
key=value
&
requests
params
import requests
url = 'https://api.example.com/search'
params = {
'query': 'Python REST API',
'page': 1,
'per_page': 10
}
response = requests.get(url, params=params)
# 实际发送的URL可能是:https://api.example.com/search?query=Python+REST+API&page=1&per_page=10
print(f"请求URL: {response.url}")
print(f"响应内容: {response.json()}")我发现
requests
params
2. 请求体(Request Body) 主要用于POST、PUT、PATCH等请求,用于向服务器提交大量数据或复杂结构的数据。
JSON数据 (json
requests
json
Content-Type: application/json
import requests
url = 'https://api.example.com/products'
payload = {
'name': '智能手表',
'category': '穿戴设备',
'price': 199.99,
'features': ['心率监测', 'GPS']
}
response = requests.post(url, json=payload)
print(f"状态码: {response.status_code}")
print(f"响应: {response.json()}")我个人觉得这是
requests
json.dumps()
表单数据 (data
Content-Type: application/x-www-form-urlencoded
data
import requests
url = 'https://api.example.com/login'
form_data = {
'username': 'myuser',
'password': 'mypassword'
}
response = requests.post(url, data=form_data)
print(f"状态码: {response.status_code}")
print(f"响应: {response.text}")data
文件上传 (files
requests
files
import requests
url = 'https://api.example.com/upload'
with open('my_document.pdf', 'rb') as f: # 以二进制模式打开文件
files = {'document': f} # 键是表单字段名,值是文件对象
response = requests.post(url, files=files)
print(f"状态码: {response.status_code}")
print(f"响应: {response.text}")这里需要注意,
files
Content-Type: multipart/form-data
'rb'
3. 请求头(Headers) 请求头用于传递元数据,比如认证信息、内容类型、用户代理等。通过
headers
import requests
url = 'https://api.example.com/profile'
headers = {
'User-Agent': 'MyCustomPythonClient/1.0',
'Accept-Language': 'zh-CN,zh;q=0.9',
'X-Request-ID': 'unique-id-12345' # 有些API会要求自定义头
}
response = requests.get(url, headers=headers)
print(f"状态码: {response.status_code}")
print(f"响应: {response.json()}")我个人在调试API时,会频繁地修改
headers
Content-Type
Authorization
理解
params
data
json
files
requests
以上就是python中如何调用REST API?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号