⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

Python API调用实战

学习API请求 · 难度:高级 · +15XP

Python API 调用实战

在现代 Web 开发中,调用 RESTful API 获取或提交数据是非常常见的需求。Python 的 requests 库是进行 HTTP 请求最流行的工具。本节将演示如何使用 requests 库与各种 API 接口进行交互,包括 GET、POST、认证、异常处理等完整流程。

安装与基本 GET 请求

# pip install requests
import requests

# 发送 GET 请求获取数据 response = requests.get('https://api.github.com/users/python') print(response.status_code) # 200 表示成功 print(response.headers['Content-Type']) # application/json; charset=utf-8

# 解析 JSON 响应 data = response.json() print(f"用户名: {data['login']}") print(f"粉丝数: {data['followers']}")

带参数的 GET 请求

import requests

# 使用 params 参数(推荐方式) params = { 'q': 'python', 'page': 1, 'per_page': 20 } response = requests.get('https://api.example.com/search', params=params) print(response.url) # 查看完整 URL

POST 请求提交数据

import requests

# 发送 JSON 数据 payload = { 'title': 'Python 教程', 'content': '学习 Python 异步编程', 'tags': ['python', 'async'] }

response = requests.post( 'https://jsonplaceholder.typicode.com/posts', json=payload # 自动设置 Content-Type 为 application/json ) print(response.status_code) # 201 Created print(response.json())

请求头与认证

import requests

# 自定义请求头 headers = { 'User-Agent': 'MyApp/1.0', 'Authorization': 'Bearer your_api_token_here' }

response = requests.get( 'https://api.example.com/protected/resource', headers=headers )

# HTTP 基本认证 response = requests.get( 'https://api.example.com/admin', auth=('username', 'password') )

异常处理与超时设置

import requests
from requests.exceptions import RequestException, Timeout

try: response = requests.get( 'https://api.example.com/data', timeout=10 # 设置超时时间(秒) ) response.raise_for_status() # 检查 HTTP 错误

data = response.json() print(f'获取到 {len(data)} 条记录')

except Timeout: print('请求超时,请检查网络连接') except RequestException as e: print(f'请求异常: {e}') except ValueError: print('JSON 解析失败')

常见 HTTP 状态码速查

状态码含义
200请求成功
201资源创建成功
204成功但无返回内容
400请求参数错误
401未认证
403无权限
404资源不存在
500服务器内部错误
Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 152 篇
0 完成
🔥 0