使用Python的requests庫調(diào)用API接口的詳細(xì)步驟
使用 Python 的requests庫調(diào)用 API 接口是開發(fā)中最常用的方式之一,它簡化了 HTTP 請求的處理流程。以下是詳細(xì)步驟和實戰(zhàn)示例,涵蓋各種常見場景:
一、準(zhǔn)備工作:安裝 requests 庫
如果尚未安裝,先通過 pip 安裝:
pip install requests
二、基本調(diào)用流程(以 RESTful API 為例)
1. 導(dǎo)入 requests 庫
import requests
2. 發(fā)送請求并獲取響應(yīng)
以調(diào)用一個獲取商品信息的 GET 接口為例:
# API地址URL
url = "https://api.example.com/products/123"
# 發(fā)送GET請求
response = requests.get(url)
# 查看響應(yīng)狀態(tài)碼(200表示成功)
print("狀態(tài)碼:", response.status_code)
# 查看響應(yīng)內(nèi)容(默認(rèn)是字符串格式)
print("響應(yīng)內(nèi)容:", response.text)
# 解析JSON格式的響應(yīng)(最常用)
if response.status_code == 200:
data = response.json() # 自動解析JSON,返回字典/列表
print("商品名稱:", data["name"])
print("商品價格:", data["price"])
三、不同請求類型的調(diào)用方式
1. GET 請求(查詢數(shù)據(jù))
常用于獲取數(shù)據(jù),參數(shù)通過 URL 的查詢字符串傳遞:
url = "https://api.example.com/products"
# 請求參數(shù)(會自動拼接到URL后面:?category=electronics&page=1)
params = {
"category": "electronics", # 商品分類
"page": 1 # 頁碼
}
# 發(fā)送帶參數(shù)的GET請求
response = requests.get(url, params=params)
# 查看最終請求的URL
print("請求URL:", response.url) # 輸出:https://api.example.com/products?category=electronics&page=1
# 解析響應(yīng)
if response.ok: # response.ok 等價于 status_code == 200
products = response.json()["data"]
for product in products:
print(product["id"], product["name"])
2. POST 請求(提交數(shù)據(jù))
常用于創(chuàng)建資源(如提交表單、創(chuàng)建訂單),數(shù)據(jù)放在請求體中:
url = "https://api.example.com/orders"
# 請求頭(告訴服務(wù)器數(shù)據(jù)格式為JSON)
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer your_token_here" # 認(rèn)證令牌(如有)
}
# 請求體數(shù)據(jù)(JSON格式)
payload = {
"product_id": 123,
"quantity": 2,
"address": "北京市朝陽區(qū)..."
}
# 發(fā)送POST請求(json參數(shù)會自動序列化并設(shè)置Content-Type為application/json)
response = requests.post(url, json=payload, headers=headers)
# 處理響應(yīng)
if response.status_code == 201: # 201表示資源創(chuàng)建成功
order = response.json()
print("創(chuàng)建訂單成功,訂單號:", order["order_id"])
else:
print("創(chuàng)建失?。?, response.text)
3. PUT/PATCH 請求(更新數(shù)據(jù))
- PUT:全量更新資源(需提供完整數(shù)據(jù))
- 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("更新成功")
4. DELETE 請求(刪除數(shù)據(jù))
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表示刪除成功(無返回內(nèi)容)
print("刪除成功")
四、處理認(rèn)證與權(quán)限
多數(shù) API 需要身份驗證,常見方式:
1. API Key 認(rèn)證
url = "https://api.example.com/data"
params = {
"api_key": "your_api_key_here" # 在查詢參數(shù)中攜帶API Key
}
response = requests.get(url, params=params)
2. Token 認(rèn)證(Bearer Token)
url = "https://api.example.com/data"
headers = {
"Authorization": "Bearer your_token_here" # 在請求頭中攜帶Token
}
response = requests.get(url, headers=headers)
3. 基礎(chǔ)認(rèn)證(Basic Auth)
url = "https://api.example.com/data"
# 傳入用戶名和密碼,requests會自動處理編碼
response = requests.get(url, auth=("username", "password"))
五、處理異常與錯誤
網(wǎng)絡(luò)請求可能遇到各種問題,需添加異常處理:
url = "https://api.example.com/products"
try:
# 設(shè)置超時時間(防止無限等待)
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權(quán)限不足、404未找到
except requests.exceptions.ConnectionError:
print("連接錯誤(可能是URL錯誤或網(wǎng)絡(luò)問題)")
except requests.exceptions.Timeout:
print("請求超時")
except requests.exceptions.RequestException as e:
print(f"其他錯誤:{e}")
else:
# 無異常時處理響應(yīng)
print("請求成功,數(shù)據(jù):", response.json())
六、高級用法
1. 會話保持(復(fù)用連接)
多次調(diào)用同一 API 時,用Session保持連接,提升效率:
# 創(chuàng)建會話對象
with requests.Session() as session:
# 會話中設(shè)置全局headers(所有請求都會攜帶)
session.headers.update({"Authorization": "Bearer your_token"})
# 第一次請求(建立連接)
response1 = session.get("https://api.example.com/products/1")
# 第二次請求(復(fù)用連接,速度更快)
response2 = session.get("https://api.example.com/products/2")
2. 上傳文件
url = "https://api.example.com/upload"
files = {
"file": open("image.jpg", "rb") # 打開文件(二進(jìn)制模式)
}
response = requests.post(url, files=files)
print("上傳結(jié)果:", response.json())
七、總結(jié)
requests庫調(diào)用 API 的核心流程是:
- 確定請求類型(GET/POST 等)和 URL;
- 準(zhǔn)備參數(shù)(params)、請求體(json/payload)、請求頭(headers);
- 發(fā)送請求并處理響應(yīng)(解析 JSON、判斷狀態(tài)碼);
- 添加異常處理確保代碼健壯性。
通過上述方法,可應(yīng)對絕大多數(shù) API 調(diào)用場景,包括電商平臺接口、支付接口、第三方服務(wù)接口等。實際開發(fā)中需結(jié)合具體 API 文檔調(diào)整參數(shù)和格式。
以上就是使用Python的requests庫調(diào)用API接口的詳細(xì)步驟的詳細(xì)內(nèi)容,更多關(guān)于Python requests調(diào)用API接口的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python中的socket網(wǎng)絡(luò)模塊介紹
這篇文章主要介紹了Python中的socket網(wǎng)絡(luò)模塊介紹,Python 中,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07
一個Python優(yōu)雅的數(shù)據(jù)分塊方法詳解
在做需求過程中有一個對大量數(shù)據(jù)分塊處理的場景,具體來說就是幾十萬量級的數(shù)據(jù),分批處理,每次處理100個。這時就需要一個分塊功能的代碼。本文為大家分享了一個Python中優(yōu)雅的數(shù)據(jù)分塊方法,需要的可以參考一下2022-05-05
Pearson相關(guān)系數(shù)和Spearman相關(guān)系數(shù)的區(qū)別及說明
這篇文章主要介紹了Pearson相關(guān)系數(shù)和Spearman相關(guān)系數(shù)的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
基于python分析你的上網(wǎng)行為 看看你平時上網(wǎng)都在干嘛
這篇文章主要介紹了基于python分析你的上網(wǎng)行為 看看你平時上網(wǎng)都在干嘛,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08
Python3.4實現(xiàn)遠(yuǎn)程控制電腦開關(guān)機(jī)
這篇文章主要為大家詳細(xì)介紹了Python3.4實現(xiàn)遠(yuǎn)程控制電腦開關(guān)機(jī)的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02
python實現(xiàn)學(xué)生成績測評系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)學(xué)生成績測評系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-06-06

