
如何快速實(shí)現(xiàn)REST API集成以優(yōu)化業(yè)務(wù)流程
小貼士: response對(duì)象包含了服務(wù)器響應(yīng)的所有信息,不僅有內(nèi)容,還有狀態(tài)碼、響應(yīng)頭等重要信息。
看看如何優(yōu)雅地處理URL參數(shù):
import requests
# 使用params參數(shù)傳遞查詢參數(shù)
params = {
'q': 'python',
'sort': 'stars',
'order': 'desc'
}
response = requests.get(
'https://api.github.com/search/repositories',
params=params
)
# 查看實(shí)際請(qǐng)求的URL
print(f"完整URL: {response.url}")
# 解析JSON響應(yīng)
data = response.json()
print(f"查找到的倉(cāng)庫(kù)數(shù)量: {data.get('total_count', 0)}")
Requests支持所有常見的HTTP方法:
import requests
# POST請(qǐng)求示例
data = {'username': 'python_lover', 'password': '12345'}
response = requests.post('https://httpbin.org/post', data=data)
# PUT請(qǐng)求示例
response = requests.put('https://httpbin.org/put', data={'key': 'value'})
# DELETE請(qǐng)求示例
response = requests.delete('https://httpbin.org/delete')
# 自定義請(qǐng)求頭
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json'
}
response = requests.get('https://api.github.com/user', headers=headers)
來看看如何處理文件操作:
import requests
# 上傳文件
def upload_file():
files = {
'file': ('test.txt', open('test.txt', 'rb'), 'text/plain')
}
response = requests.post('https://httpbin.org/post', files=files)
return response.json()
# 下載文件
def download_file(url, filename):
response = requests.get(url, stream=True)
if response.status_code == 200:
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return True
return False
# 使用示例
# download_file('https://example.com/file.pdf', 'downloaded.pdf')
使用會(huì)話來維持連接和Cookie:
import requests
# 創(chuàng)建會(huì)話對(duì)象
session = requests.Session()
# 設(shè)置會(huì)話級(jí)別的請(qǐng)求頭
session.headers.update({
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json'
})
# 使用會(huì)話發(fā)送請(qǐng)求
response = session.get('https://httpbin.org/cookies/set/sessionid/123456789')
print(f"Cookie: {session.cookies.get_dict()}")
# 后續(xù)請(qǐng)求會(huì)自動(dòng)帶上之前的Cookie
response = session.get('https://httpbin.org/cookies')
print(f"服務(wù)器看到的Cookie: {response.json()}")
優(yōu)雅地處理請(qǐng)求中可能出現(xiàn)的異常:
import requests
from requests.exceptions import RequestException
def safe_request(url):
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # 檢查響應(yīng)狀態(tài)
return response.json()
except requests.exceptions.Timeout:
print("請(qǐng)求超時(shí)")
except requests.exceptions.HTTPError as e:
print(f"HTTP錯(cuò)誤: {e}")
except requests.exceptions.RequestException as e:
print(f"請(qǐng)求出錯(cuò): {e}")
return None
# 使用示例
result = safe_request('https://api.github.com/users/invalid_user_12345')
本文章轉(zhuǎn)載微信公眾號(hào)@南南閑聊
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)