调用HTTP接口核心是理解请求方法和响应状态码;Python常用requests库,GET/POST/PUT/PATCH/DELETE对应不同操作,需关注200/201/400/401/403/404/500等状态码含义,并处理超时、异常及请求头。
调用 HTTP 接口,核心是理解 请求方法 和 响应状态码——它们决定了你“怎么发”和“服务器怎么回”。Python 中最常用的是 requests 库,简洁可靠,适合绝大多数场景。
不同请求方法对应不同的操作语义,选错可能导致接口失败或数据异常:
requests.get("https://api.example.com/users?id=123")
application/json 或 application/x-www-form-urlencoded。requests.post(url, json={"name": "Alice", "email": "a@example.com"})
requests.put(url, json={"id": 123, "name": "Alice", "age": 30})
requests.patch(url, json={"email": "new@a.com"})
requests.delete("https://api.example.com/users/123")
状态码是服务器对请求的“一句话反馈”,必须检查,不能只看 response.text:
{"code": 40001, "msg": "token 过期"} 是常见设计)。Location 指向新资源地址。
400 Bad Request:客户端参数错误(如字段缺失、类型不对、JSON 格式错误)。应检查请求数据结构和必填项。光会发请求不够,这些点常导致调试困难:
response.status_code,再决定是否解析 JSON;避免直接调用 response.json() 导致 JSONDecodeError(比如 500 返回 HTML 错误页)。requests.get(url, timeout=5),防止请求卡死。生产环境建议设 timeout=(3, 7)(连接 3 秒,读取 7 秒)。User-Agent 和认证信息:headers = {"Authorization": "Bearer xxx", "Content-Type": "application/json"}
requests.exceptions.Timeout、requests.exceptions.ConnectionError、requests.exceptions.RequestException(基类)。不追求复杂,但覆盖基本健壮性:
import requests
def api_call(method, url, **kwargs):
headers = kwargs.pop("headers", {})
headers.setdefault("User-Agent", "MyApp/1.0")
try:
resp = requests.request(method, url, timeout=(3, 10), headers=headers, **kwargs)
if resp.status_code == 200:
return resp.json()
else:
print(f"HTTP {resp.status_code}: {resp.reason}")
return {"error": "http_error", "status": resp.status_code, "detail": resp.text[:200]}
except requests.exceptions.Timeout:
print("请求超时")
return {"error": "timeout"}
except requests.exceptions.ConnectionError:
print("连接失败")
return {"error": "connection_failed"}
except Exception as e:
print(f"未知错误: {e}")
return {"error": "unknown", "detail": str(e)}