文档
Requests Hello World:GET 请求与 JSON 解析
目标
发送一个 GET 请求到公开 API,解析 JSON 响应,并处理常见 HTTP 状态码。
完整代码
import requests
# 1. 基础 GET 请求
url = "https://api.github.com/repos/psf/requests"
response = requests.get(url)
# 2. 检查状态码
print(f"状态码: {response.status_code}")
print(f"Content-Type: {response.headers['Content-Type']}")
# 3. 解析 JSON
if response.status_code == 200:
data = response.json()
print(f"仓库名: {data['full_name']}")
print(f"Stars: {data['stargazers_count']}")
print(f"描述: {data['description']}")
else:
print(f"请求失败: {response.text[:200]}")
# 4. 带 Query 参数的请求
params = {"q": "python requests", "sort": "stars"}
resp = requests.get("https://api.github.com/search/repositories", params=params)
if resp.ok:
results = resp.json()
print(f"\n搜索到 {results['total_count']} 个仓库")
for repo in results["items"][:3]:
print(f" - {repo['full_name']} ⭐{repo['stargazers_count']}")
运行步骤
pip install requests
python hello_requests.py
预期输出
状态码: 200
Content-Type: application/json; charset=utf-8
仓库名: psf/requests
Stars: 52300+
描述: A simple, yet elegant, HTTP library.
搜索到 150000+ 个仓库
- psf/requests ⭐52300+
- httpie/cli ⭐35000+
- encode/httpx ⭐14000+