# 發送GET請求
response = requests.get('https://api.github.com')

# 查看響應狀態碼
print(f"狀態碼: {response.status_code}")

# 查看響應內容
print(f"響應內容類型: {response.headers['content-type']}")
print(f"響應內容: {response.text[:100]}...") # 只顯示前100個字符

小貼士: response對象包含了服務器響應的所有信息,不僅有內容,還有狀態碼、響應頭等重要信息。

請求參數處理

看看如何優雅地處理URL參數:

import requests

# 使用params參數傳遞查詢參數
params = {
'q': 'python',
'sort': 'stars',
'order': 'desc'
}

response = requests.get(
'https://api.github.com/search/repositories',
params=params
)

# 查看實際請求的URL
print(f"完整URL: {response.url}")

# 解析JSON響應
data = response.json()
print(f"查找到的倉庫數量: {data.get('total_count', 0)}")

處理不同類型的請求

Requests支持所有常見的HTTP方法:

import requests

# POST請求示例
data = {'username': 'python_lover', 'password': '12345'}
response = requests.post('https://httpbin.org/post', data=data)

# PUT請求示例
response = requests.put('https://httpbin.org/put', data={'key': 'value'})

# DELETE請求示例
response = requests.delete('https://httpbin.org/delete')

# 自定義請求頭
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')

會話和Cookie處理

使用會話來維持連接和Cookie:

import requests

# 創建會話對象
session = requests.Session()

# 設置會話級別的請求頭
session.headers.update({
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json'
})

# 使用會話發送請求
response = session.get('https://httpbin.org/cookies/set/sessionid/123456789')
print(f"Cookie: {session.cookies.get_dict()}")

# 后續請求會自動帶上之前的Cookie
response = session.get('https://httpbin.org/cookies')
print(f"服務器看到的Cookie: {response.json()}")

異常處理

優雅地處理請求中可能出現的異常:

import requests
from requests.exceptions import RequestException

def safe_request(url):
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # 檢查響應狀態
return response.json()
except requests.exceptions.Timeout:
print("請求超時")
except requests.exceptions.HTTPError as e:
print(f"HTTP錯誤: {e}")
except requests.exceptions.RequestException as e:
print(f"請求出錯: {e}")
return None

# 使用示例
result = safe_request('https://api.github.com/users/invalid_user_12345')

實用技巧:

常見問題提醒:

練習項目建議:

  1. 創建一個簡單的天氣查詢程序
  2. 實現GitHub API的基本調用
  3. 開發一個文件下載器

本文章轉載微信公眾號@南南閑聊

上一篇:

不知道,但是可能超有用的 Web API

下一篇:

LLM之Prompt(一):5個Prompt高效方法在文心一言3.5的測試對比
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費