理解API代码:高效REST API集成的综合指南
这个Python库让API测试超简单:Requests真好用
2024-12-09
大家好啊,我是小码哥!今天要跟大家分享一个在Python中特别好用的第三方库 - **Requests**。在这个万物互联的时代,我们经常需要和各种网络API打交道。无论是调用别人的接口,还是测试自己开发的API,都离不开HTTP请求。Requests库以其简单优雅的设计,让我们处理HTTP请求变得超级简单!
## 初识Requests:安装和基本使用
我们需要安装Requests库。打开命令行,输入:
```python
pip install requests
安装完成后,我们就可以开始使用啦!先来看一个最简单的GET请求:
import requests
# 发送GET请求
response = requests.get('https://api.example.com/users')
print(response.status_code) # 打印状态码
print(response.text) # 打印响应内容
小贴士:
response.text
返回的是字符串格式,如果响应是JSON格式,可以直接用response.json()
转换成Python字典!
1.GET请求进阶:添加参数和请求头
在实际开发中,我们经常需要传递查询参数和自定义请求头。Requests让这些操作变得超级简单:
# 添加查询参数
params = {
'page': 1,
'size': 10,
'keyword': 'python'
}
headers = {
'User-Agent': 'Mozilla/5.0',
'Authorization': 'Bearer your-token'
}
response = requests.get(
'https://api.example.com/search',
params=params, # 查询参数会自动拼接到URL中
headers=headers # 自定义请求头
)
2.POST请求:发送数据
发送POST请求同样简单,Requests支持多种格式的数据:
# 发送表单数据
form_data = {
'username': 'xiaomage',
'password': '123456'
}
response = requests.post('https://api.example.com/login', data=form_data)
# 发送JSON数据
json_data = {
'name': '小码哥',
'age': 18,
'skills': ['Python', 'API测试']
}
response = requests.post('https://api.example.com/users', json=json_data)
小贴士:使用
json
参数时,Requests会自动将Python字典转换为JSON格式,并设置正确的Content-Type头部!
3.异常处理和超时设置
在网络请求中,异常处理特别重要。
来看看如何优雅地处理可能的错误:
try:
# 设置5秒超时
response = requests.get('https://api.example.com/data', timeout=5)
response.raise_for_status() # 如果状态码不是2xx,会抛出异常
except requests.exceptions.Timeout:
print('请求超时了!')
except requests.exceptions.RequestException as e:
print(f'遇到错误啦:{e}')
4.会话管理:保持登录状态
如果需要维持登录状态或者复用TCP连接,可以使用会话(Session)对象:
# 创建会话
session = requests.Session()
# 登录
session.post('https://api.example.com/login', data={'username': 'xiaomage'})
# 后续请求会自动带上登录信息(比如Cookie)
response = session.get('https://api.example.com/profile')
5.实战小练习
来做个小练习吧!调用免费的天气API获取天气信息:
import requests
def get_weather(city):
“”“获取城市天气信息”“”
url = f'http://wthrcdn.etouch.cn/weather_mini?city={city}'
try:
response = requests.get(url)
data = response.json()
if data['status'] == 1000:
weather = data['data']['forecast'][0]
return f“{city}今天{weather['type']},{weather['low']}到{weather['high']}”
return f“未找到{city}的天气信息”
except Exception as e:
return f“获取天气信息失败:{e}”
# 测试一下
print(get_weather('北京'))
本文章转载微信公众号@小七学Python
同话题下的热门内容