API(Application Programming Interface)是一种软件中介,允许两个应用程序相互通信。通过API,我们可以从远程服务器获取数据或将数据发送到服务器。常见的API使用格式是REST(Representational State Transfer)风格,它使用HTTP协议进行通信。
以下是详细的讲解和Python案例,演示如何使用requests
库与API进行数据交互。
1. API基础
一个典型的REST API具有以下特点:
- 端点(Endpoint):URL地址,用于访问资源。
- 方法(Methods):HTTP动词,如GET、POST、PUT、DELETE。
- 请求头(Headers):附加信息,如认证信息、数据格式。
- 请求体(Body):发送的数据,通常用于POST或PUT请求。
2. 发送GET请求
GET请求用于从服务器获取数据。下面是一个示例,演示如何使用GET请求从API获取数据。
示例:获取GitHub用户信息
import requests
# 发送GET请求获取GitHub用户信息
response = requests.get('https://api.github.com/users/octocat')
# 处理响应
if response.status_code == 200:
user_info = response.json()
print(f"用户名: {user_info['login']}")
print(f"用户ID: {user_info['id']}")
print(f"用户URL: {user_info['html_url']}")
else:
print(f"请求失败,状态码: {response.status_code}")
3. 发送POST请求
POST请求用于向服务器发送数据。下面是一个示例,演示如何使用POST请求向API发送数据。
示例:在JSONPlaceholder创建帖子
import requests
# 数据
data = {
'title': 'foo',
'body': 'bar',
'userId': 1
}
# 发送POST请求创建帖子
response = requests.post('https://jsonplaceholder.typicode.com/posts', json=data)
# 处理响应
if response.status_code == 201:
post_info = response.json()
print(f"帖子ID: {post_info['id']}")
print(f"标题: {post_info['title']}")
print(f"内容: {post_info['body']}")
else:
print(f"请求失败,状态码: {response.status_code}")
4. 发送PUT请求
PUT请求用于更新服务器上的资源。下面是一个示例,演示如何使用PUT请求更新API中的数据。
示例:在JSONPlaceholder更新帖子
import requests
# 数据
data = {
'id': 1,
'title': 'foo updated',
'body': 'bar updated',
'userId': 1
}
# 发送PUT请求更新帖子
response = requests.put('https://jsonplaceholder.typicode.com/posts/1', json=data)
# 处理响应
if response.status_code == 200:
updated_post_info = response.json()
print(f"帖子ID: {updated_post_info['id']}")
print(f"标题: {updated_post_info['title']}")
print(f"内容: {updated_post_info['body']}")
else:
print(f"请求失败,状态码: {response.status_code}")
5. 发送DELETE请求
DELETE请求用于删除服务器上的资源。下面是一个示例,演示如何使用DELETE请求删除API中的数据。
示例:在JSONPlaceholder删除帖子
import requests
# 发送DELETE请求删除帖子
response = requests.delete('https://jsonplaceholder.typicode.com/posts/1')
# 处理响应
if response.status_code == 200:
print("帖子已删除")
else:
print(f"请求失败,状态码: {response.status_code}")
6. 使用查询参数
在GET请求中,可以使用查询参数来过滤或排序数据。下面是一个示例,演示如何使用查询参数。
示例:获取GitHub用户的仓库列表
import requests
# 查询参数
params = {
'sort': 'created',
'direction': 'desc'
}
# 发送GET请求获取GitHub用户的仓库列表
response = requests.get('https://api.github.com/users/octocat/repos', params=params)
# 处理响应
if response.status_code == 200:
repos = response.json()
for repo in repos:
print(f"仓库名: {repo['name']}, 创建时间: {repo['created_at']}")
else:
print(f"请求失败,状态码: {response.status_code}")
7. 可运行的Python案例
下面是一个完整的Python程序,演示了如何使用requests
库与API进行数据交互,包括GET、POST、PUT、DELETE请求和使用查询参数。
import requests
# 1. 发送GET请求获取GitHub用户信息
response = requests.get('https://api.github.com/users/octocat')
if response.status_code == 200:
user_info = response.json()
print("GET请求 - GitHub用户信息:")
print(f"用户名: {user_info['login']}")
print(f"用户ID: {user_info['id']}")
print(f"用户URL: {user_info['html_url']}")
else:
print(f"请求失败,状态码: {response.status_code}")
# 2. 发送POST请求在JSONPlaceholder创建帖子
data = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = requests.post('https://jsonplaceholder.typicode.com/posts', json=data)
if response.status_code == 201:
post_info = response.json()
print("\nPOST请求 - 创建帖子:")
print(f"帖子ID: {post_info['id']}")
print(f"标题: {post_info['title']}")
print(f"内容: {post_info['body']}")
else:
print(f"请求失败,状态码: {response.status_code}")
# 3. 发送PUT请求在JSONPlaceholder更新帖子
data = {'id': 1, 'title': 'foo updated', 'body': 'bar updated', 'userId': 1}
response = requests.put('https://jsonplaceholder.typicode.com/posts/1', json=data)
if response.status_code == 200:
updated_post_info = response.json()
print("\nPUT请求 - 更新帖子:")
print(f"帖子ID: {updated_post_info['id']}")
print(f"标题: {updated_post_info['title']}")
print(f"内容: {updated_post_info['body']}")
else:
print(f"请求失败,状态码: {response.status_code}")
# 4. 发送DELETE请求在JSONPlaceholder删除帖子
response = requests.delete('https://jsonplaceholder.typicode.com/posts/1')
if response.status_code == 200:
print("\nDELETE请求 - 帖子已删除")
else:
print(f"请求失败,状态码: {response.status_code}")
# 5. 使用查询参数发送GET请求获取GitHub用户的仓库列表
params = {'sort': 'created', 'direction': 'desc'}
response = requests.get('https://api.github.com/users/octocat/repos', params=params)
if response.status_code == 200:
repos = response.json()
print("\nGET请求(带查询参数) - GitHub用户的仓库列表:")
for repo in repos:
print(f"仓库名: {repo['name']}, 创建时间: {repo['created_at']}")
else:
print(f"请求失败,状态码: {response.status_code}")
可以将上面的代码复制到你的IDE中运行,观察程序的输出。这个案例综合了API数据交互的基本知识,帮助你理解和掌握这些操作。继续加油,学习Python会越来越有趣和有用!