掌握使用 requests 库发送各种 HTTP 请求和处理 API 响应

简介: 本课程全面讲解了使用 Python 的 requests 库进行 API 请求与响应处理,内容涵盖环境搭建、GET 与 POST 请求、参数传递、错误处理、请求头设置及实战项目开发。通过实例教学,学员可掌握基础到高级技巧,并完成天气查询应用等实际项目,适合初学者快速上手网络编程与 API 调用。


上午 (9:00 - 12:00): 基础概念与核心方法

主题一:环境搭建与基础概念 (30分钟)

  1. 安装 requests
    bash

pip install requests

  1. 导入库
    python

import requests

  1. HTTP 基础概念
  • URL结构协议://域名/路径?参数=值
  • 主要HTTP方法
  • GET - 获取资源(最常用)
  • POST - 创建资源
  • PUT - 更新资源
  • DELETE - 删除资源
  • 常见状态码
  • 200 - 成功
  • 201 - 创建成功
  • 400 - 错误请求
  • 404 - 未找到
  • 500 - 服务器错误

主题二:发送第一个 GET 请求 (1小时)

python

# 最基本的 GET 请求

response = requests.get('https://httpbin.org/get')

print(f"状态码: {response.status_code}")

print(f"响应内容: {response.text}")


# 检查请求是否成功

if response.status_code == 200:

   print('✅ 请求成功!')

   # 解析 JSON 响应

   data = response.json()

   print(data)

else:

   print(f'❌ 请求失败,状态码:{response.status_code}')

主题三:带参数的 GET 请求 (45分钟)

python

# 方法1:直接在URL中添加参数

response = requests.get('https://httpbin.org/get?name=John&age=30')


# 方法2:使用 params 参数(推荐,更清晰)

params = {

   'name': 'John',

   'age': 30,

   'city': 'New York'

}

response = requests.get('https://httpbin.org/get', params=params)


print(f"最终请求URL: {response.url}")

print(f"响应JSON: {response.json()}")

动手练习:尝试调用这些测试API:


下午 (13:30 - 18:00): 高级功能与实战

主题四:处理响应内容 (1小时)

python

response = requests.get('https://api.github.com/users/octocat')


print(f"状态码: {response.status_code}")

print(f"状态消息: {response.reason}")

print(f"内容类型: {response.headers['Content-Type']}")


# 检查内容类型并相应处理

if 'application/json' in response.headers['Content-Type']:

   data = response.json()  # 解析为Python字典

   print(f"用户名: {data['login']}")

   print(fID: {data['id']}")

   print(f"头像URL: {data['avatar_url']}")

else:

   print("响应不是JSON格式")

   print(response.text)

主题五:错误处理与超时设置 (45分钟)

python

import requests

from requests.exceptions import RequestException


try:

   # 设置超时时间(连接超时5秒,读取超时10秒)

   response = requests.get('https://api.github.com/user', timeout=(5, 10))

   response.raise_for_status()  # 如果状态码不是200,抛出异常

   

   data = response.json()

   print("请求成功!")

   print(data)

   

except requests.exceptions.Timeout:

   print("⏰ 请求超时!请检查网络连接")

except requests.exceptions.ConnectionError:

   print("🔌 网络连接错误!")

except requests.exceptions.HTTPError as err:

   print(f"❌ HTTP错误:{err}")

   print(f"状态码:{response.status_code}")

except RequestException as err:

   print(f"⚠️ 其他请求错误:{err}")

主题六:请求头设置 (45分钟)

python

headers = {

   'User-Agent': 'MyPythonApp/1.0 (learning-requests)',  # 标识你的应用

   'Accept': 'application/json',

   'Content-Type': 'application/json'

}


# 使用自定义请求头

response = requests.get(

   'https://httpbin.org/headers',

   headers=headers,

   timeout=10

)


print("服务器接收到的请求头:")

print(response.json()['headers'])

主题七:发送 POST 请求 (1小时)

python

# 1. 发送表单数据

form_data = {

   'username': 'testuser',

   'password': 'testpass123',

   'email': 'test@example.com'

}


response = requests.post('https://httpbin.org/post', data=form_data)

print("表单POST响应:")

print(response.json())


# 2. 发送 JSON 数据

json_data = {

   'name': 'John Doe',

   'age': 30,

   'hobbies': ['reading', 'swimming', 'coding']

}


response = requests.post('https://httpbin.org/post', json=json_data)

print("\nJSON POST响应:")

print(response.json())


晚上 (19:00 - 21:00): 综合实战项目

主题八:实战项目 - 天气查询应用 (2小时)

python

import requests

import json


class WeatherApp:

   def __init__(self, api_key):

       self.api_key = api_key

       self.base_url = "http://api.openweathermap.org/data/2.5/weather"

   

   def get_weather(self, city_name):

       """获取城市天气信息"""

       params = {

           'q': city_name,

           'appid': self.api_key,

           'units': 'metric',  # 公制单位

           'lang': 'zh_cn'     # 中文显示

       }

       

       try:

           response = requests.get(self.base_url, params=params, timeout=10)

           response.raise_for_status()

           

           data = response.json()

           return self._parse_weather_data(data)

           

       except requests.exceptions.RequestException as e:

           return f"获取天气信息失败:{e}"

   

   def _parse_weather_data(self, data):

       """解析天气数据"""

       return {

           'city': data['name'],

           'temperature': data['main']['temp'],

           'feels_like': data['main']['feels_like'],

           'description': data['weather'][0]['description'],

           'humidity': data['main']['humidity'],

           'wind_speed': data['wind']['speed']

       }

   

   def display_weather(self, weather_info):

       """显示天气信息"""

       if isinstance(weather_info, dict):

           print(f"\n🌤️ {weather_info['city']}的天气信息:")

           print(f"🌡️ 温度:{weather_info['temperature']}°C")

           print(f"🤔 体感温度:{weather_info['feels_like']}°C")

           print(f"☁️ 天气状况:{weather_info['description']}")

           print(f"💧湿度:{weather_info['humidity']}%")

           print(f"💨风速:{weather_info['wind_speed']} m/s")

       else:

           print(weather_info)


# 使用示例

if __name__ == "__main__":

   # 注意:需要到 openweathermap.org 注册获取免费API key

   app = WeatherApp("your_api_key_here")

   

   while True:

       city = input("\n请输入城市名称(输入quit退出): ")

       if city.lower() == 'quit':

           break

       

       weather_info = app.get_weather(city)

       app.display_weather(weather_info)

免费API资源推荐

  1. JSONPlaceholder - 免费的测试API:https://jsonplaceholder.typicode.com/
  2. HTTPBin - HTTP请求测试:https://httpbin.org/
  3. GitHub API - 无需认证:https://api.github.com/users/octocat
  4. OpenWeatherMap - 天气API(免费注册):https://openweathermap.org/api

主题九:扩展练习

  1. 创建API监控脚本:定期检查网站是否可访问
  2. 构建简单的API客户端:调用多个API并整合数据
  3. 处理分页响应:学习处理多页数据的API

学习要点总结

技能点 关键代码 说明
GET请求 requests.get(url, params, headers) 获取数据
POST请求 requests.post(url, data, json) 发送数据
错误处理 try-except + raise_for_status() 健壮性
超时设置 timeout=(5, 10) 避免长时间等待
JSON处理 response.json() 解析API响应
请求头 headers={'User-Agent': '...'} 自定义请求

今日学习成果检查

完成今天学习后,你应该能够:

  • ✅ 使用 requests 发送 GET 和 POST 请求
  • ✅ 处理 API 响应和错误
  • ✅ 设置请求参数和请求头
  • ✅ 构建一个完整的 API 客户端应用

现在开始动手实践吧!从最简单的 requests.get() 开始,逐步构建更复杂的功能。记得多写代码、多测试!

相关文章
|
4月前
|
JSON API 数据格式
1688店铺订单列表订单详情订单物流API响应数据解析
1688平台作为阿里巴巴旗下的B2B电商利器,提供高效订单管理API,支持订单查询、状态变更与物流同步,助力企业提升运营效率。本文附Python请求示例代码,实现便捷对接与数据获取。
|
2月前
|
Ubuntu API C++
C++标准库、Windows API及Ubuntu API的综合应用
总之,C++标准库、Windows API和Ubuntu API的综合应用是一项挑战性较大的任务,需要开发者具备跨平台编程的深入知识和丰富经验。通过合理的架构设计和有效的工具选择,可以在不同的操作系统平台上高效地开发和部署应用程序。
157 11
|
3月前
|
JSON 监控 测试技术
亚马逊:调用订单退款API自动化处理售后请求,缩短用户等待时间
在电商运营中,售后效率直接影响用户体验与平台声誉。亚马逊订单退款API为卖家提供自动化工具,通过编程方式高效处理退款请求,显著缩短用户等待时间。本文详解如何集成该API,实现退款流程自动化,提升响应速度与用户满意度。
167 0
|
4月前
|
人工智能 JSON JavaScript
【干货满满】API接口请求封装
在 Vue 项目中,常使用 Axios 与后台交互,它基于 Promise,支持浏览器和 Node.js,具备拦截请求、取消请求、JSON 转换等功能。本文介绍了 Axios 的安装、封装及使用方法,包括创建实例、请求拦截、响应处理、API 管理等内容,并提供了完整代码示例,便于统一管理和调用接口,适用于前后端分离开发模式。
|
4月前
|
JSON 监控 BI
京东店铺所有商品API响应数据解析
京东店铺商品API由京东开放平台提供,可获取指定店铺的商品基础信息、价格、库存及销量等数据,适用于商品管理、竞品分析、价格监控等场景。支持HTTPS请求、JSON格式返回,提供Python示例,便于第三方系统集成与数据应用。
|
4月前
|
JSON 搜索推荐 API
京东图片搜索相似商品API响应数据解析
京东图片搜索API(拍立淘)基于图像识别技术,支持通过图片或URL搜索相似商品,提供多维度筛选与商品详情提取功能,广泛应用于商品检索场景。
|
4月前
|
机器学习/深度学习 JSON API
淘宝图片搜索相似商品API响应数据解析
淘宝拍立淘API是基于深度学习的图像搜索接口,支持上传图片查找相似商品,适用于电商导购、比价、时尚搭配等场景。提供多格式支持、高精度搜索结果,返回JSON格式数据,附Python调用示例,便于快速集成。
|
Web App开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
TCP洪水攻击(SYN Flood)的诊断和处理 Posted by  海涛  on 2013 年 7 月 11 日 Tweet1 ​1. SYN Flood介绍 前段时间网站被攻击多次,其中最猛烈的就是TCP洪水攻击,即SYN Flood。
1178 0
|
Web App开发 存储 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
      前段时间公司hadoop集群宕机,发现是namenode磁盘满了, 清理出部分空间后,重启集群时,重启失败。 又发现集群Secondary namenode 服务也恰恰坏掉,导致所有的操作log持续写入edits.new 文件,等集群宕机的时候文件大小已经达到了丧心病狂的70G+..重启集群报错 加载edits文件失败。
1064 0