文章目录
- import requests
- 以调用一个获取商品信息的 GET 接口为例: # API地址URL url = “https://api.example.com/products/123” # 发送GET请求 response = requests.get(url) # 查看响应状态码(200表示成功) print(“状态码:”, response.status_code) # 查看响应内容(默认是字符串格式) print(“响应内容:”, response.text) # 解析JSON格式的响应(最常用) if response.status_code == 200: data = response.json() # 自动解析JSON,返回字典/列表 print(“商品名称:”, data[“name”]) print(“商品价格:”, data[“price”])
- 常用于获取数据,参数通过 URL 的查询字符串传递: url = “https://api.example.com/products” # 请求参数(会自动拼接到URL后面:?category=electronics&page=1) params = { “category”: “electronics”, # 商品分类 “page”: 1 # 页码 } # 发送带参数的GET请求 response = requests.get(url, params=params) # 查看最终请求的URL print(“请求URL:”, response.url) # 输出:https://api.example.com/products?category=electronics&page=1 # 解析响应 if response.ok: # response.ok 等价于 status_code == 200 products = response.json()[“data”] for product in products: print(product[“id”], product[“name”])
- 常用于创建资源(如提交表单、创建订单),数据放在请求体中: url = “https://api.example.com/orders” # 请求头(告诉服务器数据格式为JSON) headers = { “Content-Type”: “application/json”, “Authorization”: “Bearer your_token_here” # 认证令牌(如有) } # 请求体数据(JSON格式) payload = { “product_id”: 123, “quantity”: 2, “address”: “北京市朝阳区…” } # 发送POST请求(json参数会自动序列化并设置Content-Type为application/json) response = requests.post(url, json=payload, headers=headers) # 处理响应 if response.status_code == 201: # 201表示资源创建成功 order = response.json() print(“创建订单成功,订单号:”, order[“order_id”]) else: print(“创建失败:”, response.text)
- PUT:全量更新资源(需提供完整数据) PATCH:部分更新资源(仅提供需修改的字段) # 更新商品价格(PATCH示例) url = “https://api.example.com/products/123” headers = {“Authorization”: “Bearer your_token_here”} payload = {“price”: 3999} # 仅更新价格字段 response = requests.patch(url, json=payload, headers=headers) if response.ok: print(“更新成功”)
- url = “https://api.example.com/products/123” headers = {“Authorization”: “Bearer your_token_here”} response = requests.delete(url, headers=headers) if response.status_code == 204: # 204表示删除成功(无返回内容) print(“删除成功”)
- url = “https://api.example.com/data” params = { “api_key”: “your_api_key_here” # 在查询参数中携带API Key } response = requests.get(url, params=params)
- url = “https://api.example.com/data” headers = { “Authorization”: “Bearer your_token_here” # 在请求头中携带Token } response = requests.get(url, headers=headers)
- url = “https://api.example.com/data” # 传入用户名和密码,requests会自动处理编码 response = requests.get(url, auth=(“username”, “password”))
- 多次调用同一 API 时,用Session保持连接,提升效率: # 创建会话对象 with requests.Session() as session: # 会话中设置全局headers(所有请求都会携带) session.headers.update({“Authorization”: “Bearer your_token”}) # 第一次请求(建立连接) response1 = session.get(“https://api.example.com/products/1”) # 第二次请求(复用连接,速度更快) response2 = session.get(“https://api.example.com/products/2”)
- url = “https://api.example.com/upload” files = { “file”: open(“image.jpg”, “rb”) # 打开文件(二进制模式) } response = requests.post(url, files=files) print(“上传结果:”, response.json())
目录
- 一、准备工作:安装 requests 库
- 二、基本调用流程(以 RESTful API 为例)
- 1. 导入 requests 库
- 2. 发送请求并获取响应
- 三、不同请求类型的调用方式
- 1. GET 请求(查询数据)
- 2. POST 请求(提交数据)
- 3. PUT/PATCH 请求(更新数据)
- 4. DELETE 请求(删除数据)
- 四、处理认证与权限
- 1. API Key 认证
- 2. Token 认证(Bearer Token)
- 3. 基础认证(Basic Auth)
- 五、处理异常与错误
- 六、高级用法
- 1. 会话保持(复用连接)
- 2. 上传文件
- 七、总结
使用 Python 的requests库调用 API 接口是开发中最常用的方式之一,它简化了 HTTP 请求的处理流程。以下是详细步骤和实战示例,涵盖各种常见场景:
如果尚未安装,先通过 pip 安装:
pip install requests
import requests
以调用一个获取商品信息的 GET 接口为例:
# API地址URL
url = "https://api.example.com/products/123"
# 发送GET请求
response = requests.get(url)
# 查看响应状态码(200表示成功)
print("状态码:", response.status_code)
# 查看响应内容(默认是字符串格式)
print("响应内容:", response.text)
# 解析JSON格式的响应(最常用)
if response.status_code == 200:
data = response.json() # 自动解析JSON,返回字典/列表
print("商品名称:", data["name"])
print("商品价格:", data["price"])
常用于获取数据,参数通过 URL 的查询字符串传递:
url = "https://api.example.com/products"
# 请求参数(会自动拼接到URL后面:?category=electronics&page=1)
params = {
"category": "electronics", # 商品分类
"page": 1 # 页码
}
# 发送带参数的GET请求
response = requests.get(url, params=params)
# 查看最终请求的URL
print("请求URL:", response.url) # 输出:https://api.example.com/products?category=electronics&page=1
# 解析响应
if response.ok: # response.ok 等价于 status_code == 200
products = response.json()["data"]
for product in products:
print(product["id"], product["name"])
常用于创建资源(如提交表单、创建订单),数据放在请求体中:
url = "https://api.example.com/orders"
# 请求头(告诉服务器数据格式为JSON)
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer your_token_here" # 认证令牌(如有)
}
# 请求体数据(JSON格式)
payload = {
"product_id": 123,
"quantity": 2,
"address": "北京市朝阳区..."
}
# 发送POST请求(json参数会自动序列化并设置Content-Type为application/json)
response = requests.post(url, json=payload, headers=headers)
# 处理响应
if response.status_code == 201: # 201表示资源创建成功
order = response.json()
print("创建订单成功,订单号:", order["order_id"])
else:
print("创建失败:", response.text)
- PUT:全量更新资源(需提供完整数据)
- PATCH:部分更新资源(仅提供需修改的字段)
# 更新商品价格(PATCH示例)
url = "https://api.example.com/products/123"
headers = {"Authorization": "Bearer your_token_here"}
payload = {"price": 3999} # 仅更新价格字段
response = requests.patch(url, json=payload, headers=headers)
if response.ok:
print("更新成功")
url = "https://api.example.com/products/123"
headers = {"Authorization": "Bearer your_token_here"}
response = requests.delete(url, headers=headers)
if response.status_code == 204: # 204表示删除成功(无返回内容)
print("删除成功")
多数 API 需要身份验证,常见方式:
url = "https://api.example.com/data"
params = {
"api_key": "your_api_key_here" # 在查询参数中携带API Key
}
response = requests.get(url, params=params)
url = "https://api.example.com/data"
headers = {
"Authorization": "Bearer your_token_here" # 在请求头中携带Token
}
response = requests.get(url, headers=headers)
url = "https://api.example.com/data"
# 传入用户名和密码,requests会自动处理编码
response = requests.get(url, auth=("username", "password"))
网络请求可能遇到各种问题,需添加异常处理:
url = "https://api.example.com/products"
try:
# 设置超时时间(防止无限等待)
response = requests.get(url, timeout=10) # 10秒超时
# 主动抛出HTTP错误(如404、500)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(f"HTTP错误:{e}") # 如401权限不足、404未找到
except requests.exceptions.ConnectionError:
print("连接错误(可能是URL错误或网络问题)")
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.RequestException as e:
print(f"其他错误:{e}")
else:
# 无异常时处理响应
print("请求成功,数据:", response.json())
多次调用同一 API 时,用Session保持连接,提升效率:
# 创建会话对象
with requests.Session() as session:
# 会话中设置全局headers(所有请求都会携带)
session.headers.update({"Authorization": "Bearer your_token"})
# 第一次请求(建立连接)
response1 = session.get("https://api.example.com/products/1")
# 第二次请求(复用连接,速度更快)
response2 = session.get("https://api.example.com/products/2")
url = "https://api.example.com/upload"
files = {
"file": open("image.jpg", "rb") # 打开文件(二进制模式)
}
response = requests.post(url, files=files)
print("上传结果:", response.json())
requests库调用 API 的核心流程是:
- 确定请求类型(GET/POST 等)和 URL;
- 准备参数(params)、请求体(json/payload)、请求头(headers);
- 发送请求并处理响应(解析 JSON、判断状态码);
- 添加异常处理确保代码健壮性。
通过上述方法,可应对绝大多数 API 调用场景,包括电商平台接口、支付接口、第三方服务接口等。实际开发中需结合具体 API 文档调整参数和格式。
以上就是使用Python的requests库调用API接口的详细步骤的详细内容,更多关于Python requests调用API接口的资料请关注风君子博客其它相关文章!
您可能感兴趣的文章:
- python+requests+unittest API接口测试实例(详解)
- Python调用requests库实现自动化发牌功能
- Python requests下载文件的几种常用方法(附代码)
- 一文详解如何在Python中使用Requests库