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

# 查看響應(yīng)狀態(tài)碼
print(f"狀態(tài)碼: {response.status_code}")

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

小貼士: response對(duì)象包含了服務(wù)器響應(yīng)的所有信息,不僅有內(nèi)容,還有狀態(tài)碼、響應(yīng)頭等重要信息。

請(qǐng)求參數(shù)處理

看看如何優(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)}")

處理不同類型的請(qǐng)求

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處理

使用會(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')

實(shí)用技巧:

常見問題提醒:

練習(xí)項(xiàng)目建議:

  1. 創(chuàng)建一個(gè)簡(jiǎn)單的天氣查詢程序
  2. 實(shí)現(xiàn)GitHub API的基本調(diào)用
  3. 開發(fā)一個(gè)文件下載器

本文章轉(zhuǎn)載微信公眾號(hào)@南南閑聊

上一篇:

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

下一篇:

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

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)