
如何快速實(shí)現(xiàn)REST API集成以優(yōu)化業(yè)務(wù)流程
安裝完成后,我們就可以開(kāi)始使用啦!先來(lái)看一個(gè)最簡(jiǎn)單的GET請(qǐng)求:
import requests
# 發(fā)送GET請(qǐng)求
response = requests.get('https://api.example.com/users')
print(response.status_code) # 打印狀態(tài)碼
print(response.text) # 打印響應(yīng)內(nèi)容
小貼士:
response.text
返回的是字符串格式,如果響應(yīng)是JSON格式,可以直接用response.json()
轉(zhuǎn)換成Python字典!
在實(shí)際開(kāi)發(fā)中,我們經(jīng)常需要傳遞查詢參數(shù)和自定義請(qǐng)求頭。Requests讓這些操作變得超級(jí)簡(jiǎn)單:
# 添加查詢參數(shù)
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, # 查詢參數(shù)會(huì)自動(dòng)拼接到URL中
headers=headers # 自定義請(qǐng)求頭
)
# 發(fā)送表單數(shù)據(jù)
form_data = {
'username': 'xiaomage',
'password': '123456'
}
response = requests.post('https://api.example.com/login', data=form_data)
# 發(fā)送JSON數(shù)據(jù)
json_data = {
'name': '小碼哥',
'age': 18,
'skills': ['Python', 'API測(cè)試']
}
response = requests.post('https://api.example.com/users', json=json_data)
小貼士:使用
json
參數(shù)時(shí),Requests會(huì)自動(dòng)將Python字典轉(zhuǎn)換為JSON格式,并設(shè)置正確的Content-Type頭部!
來(lái)看看如何優(yōu)雅地處理可能的錯(cuò)誤:
try:
# 設(shè)置5秒超時(shí)
response = requests.get('https://api.example.com/data', timeout=5)
response.raise_for_status() # 如果狀態(tài)碼不是2xx,會(huì)拋出異常
except requests.exceptions.Timeout:
print('請(qǐng)求超時(shí)了!')
except requests.exceptions.RequestException as e:
print(f'遇到錯(cuò)誤啦:{e}')
如果需要維持登錄狀態(tài)或者復(fù)用TCP連接,可以使用會(huì)話(Session)對(duì)象:
# 創(chuàng)建會(huì)話
session = requests.Session()
# 登錄
session.post('https://api.example.com/login', data={'username': 'xiaomage'})
# 后續(xù)請(qǐng)求會(huì)自動(dòng)帶上登錄信息(比如Cookie)
response = session.get('https://api.example.com/profile')
來(lái)做個(gè)小練習(xí)吧!調(diào)用免費(fèi)的天氣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}”
# 測(cè)試一下
print(get_weather('北京'))
本文章轉(zhuǎn)載微信公眾號(hào)@小七學(xué)Python
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)