
如何快速實現REST API集成以優化業務流程
安裝完成后,我們就可以開始使用啦!先來看一個最簡單的GET請求:
import requests
# 發送GET請求
response = requests.get('https://api.example.com/users')
print(response.status_code) # 打印狀態碼
print(response.text) # 打印響應內容
小貼士:
response.text
返回的是字符串格式,如果響應是JSON格式,可以直接用response.json()
轉換成Python字典!
在實際開發中,我們經常需要傳遞查詢參數和自定義請求頭。Requests讓這些操作變得超級簡單:
# 添加查詢參數
params = {
'page': 1,
'size': 10,
'keyword': 'python'
}
headers = {
'User-Agent': 'Mozilla/5.0',
'Authorization': 'Bearer your-token'
}
response = requests.get(
'https://api.example.com/search',
params=params, # 查詢參數會自動拼接到URL中
headers=headers # 自定義請求頭
)
# 發送表單數據
form_data = {
'username': 'xiaomage',
'password': '123456'
}
response = requests.post('https://api.example.com/login', data=form_data)
# 發送JSON數據
json_data = {
'name': '小碼哥',
'age': 18,
'skills': ['Python', 'API測試']
}
response = requests.post('https://api.example.com/users', json=json_data)
小貼士:使用
json
參數時,Requests會自動將Python字典轉換為JSON格式,并設置正確的Content-Type頭部!
來看看如何優雅地處理可能的錯誤:
try:
# 設置5秒超時
response = requests.get('https://api.example.com/data', timeout=5)
response.raise_for_status() # 如果狀態碼不是2xx,會拋出異常
except requests.exceptions.Timeout:
print('請求超時了!')
except requests.exceptions.RequestException as e:
print(f'遇到錯誤啦:{e}')
如果需要維持登錄狀態或者復用TCP連接,可以使用會話(Session)對象:
# 創建會話
session = requests.Session()
# 登錄
session.post('https://api.example.com/login', data={'username': 'xiaomage'})
# 后續請求會自動帶上登錄信息(比如Cookie)
response = session.get('https://api.example.com/profile')
來做個小練習吧!調用免費的天氣API獲取天氣信息:
import requests
def get_weather(city):
“”“獲取城市天氣信息”“”
url = f'http://wthrcdn.etouch.cn/weather_mini?city={city}'
try:
response = requests.get(url)
data = response.json()
if data['status'] == 1000:
weather = data['data']['forecast'][0]
return f“{city}今天{weather['type']},{weather['low']}到{weather['high']}”
return f“未找到{city}的天氣信息”
except Exception as e:
return f“獲取天氣信息失敗:{e}”
# 測試一下
print(get_weather('北京'))
本文章轉載微信公眾號@小七學Python