代理开发者的 REST API 基础
HTTP 方法、状态码、请求头以及 JSON 请求/响应格式。
代理开发者的 REST API 基础 是 CoddyKit 上的免费 AI Agents 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。
什么是 HTTP 请求
每个连接外部服务的智能体都会使用超文本传输协议——Web 的语言。一个 HTTP 请求包含三个关键部分:方法、URL以及可选的标头和请求体。
您可以把方法理解为告诉服务器您想做什么的动词,把 URL 理解为资源的地址。
import requests
# A simple GET request to a public API
response = requests.get('https://api.example.com/users')
print(response.status_code) # 200
print(response.text) # raw JSON stringGET — 获取数据
GET 从服务器获取数据。它不应修改任何内容。智能体使用 GET 读取用户资料、获取任务列表或拉取配置数据。
您可以使用 params 参数,将参数作为查询字符串传入 URL。
import requests
# Fetch users filtered by role
params = {'role': 'admin', 'page': 1, 'limit': 10}
response = requests.get(
'https://api.example.com/users',
params=params
)
# URL becomes: /users?role=admin&page=1&limit=10
data = response.json()
print(data['users'])POST — 创建资源
POST 向服务器发送数据,以创建新资源。智能体使用 POST 提交任务、发送消息或触发操作。数据以 JSON 的形式放在请求体中。
请始终设置 Content-Type: application/json 标头——大多数 API 都要求这样做。
import requests
import json
payload = {
'title': 'Research competitors',
'assignee': 'agent-001',
'priority': 'high'
}
response = requests.post(
'https://api.example.com/tasks',
json=payload # sets Content-Type automatically
)
print(response.status_code) # 201 Created
new_task = response.json()
print('Created task ID:', new_task['id'])PUT 与 PATCH — 更新数据
PUT 使用新数据替换整个资源。PATCH 只更新特定字段。当智能体拥有完整的更新对象时使用 PUT;对于更新任务状态这类局部变更,则使用 PATCH。
import requests
task_id = '42'
# PATCH: only update the status field
response = requests.patch(
f'https://api.example.com/tasks/{task_id}',
json={'status': 'completed'}
)
print(response.status_code) # 200
# PUT: replace the whole task object
full_task = {
'title': 'Research competitors',
'assignee': 'agent-001',
'priority': 'low',
'status': 'completed'
}
response = requests.put(
f'https://api.example.com/tasks/{task_id}',
json=full_task
)
print(response.status_code) # 200DELETE — 移除资源
DELETE 从服务器移除资源。智能体使用 DELETE 清理临时数据、移除已处理的任务或取消计划中的作业。大多数 DELETE 请求没有请求体。
成功的删除操作通常返回 204 No Content——响应中没有请求体。
import requests
task_id = '42'
response = requests.delete(
f'https://api.example.com/tasks/{task_id}'
)
if response.status_code == 204:
print('Task deleted successfully')
elif response.status_code == 404:
print('Task not found — already deleted?')
else:
print('Unexpected status:', response.status_code)状态码:2xx 成功
状态码会告诉您的智能体请求是成功还是失败。2xx 范围表示成功:
200 OK— GET/PUT/PATCH 返回了数据201 Created— POST 创建了新资源204 No Content— DELETE 成功,没有返回请求体
处理响应请求体之前,请始终检查状态码。
import requests
response = requests.post(
'https://api.example.com/tasks',
json={'title': 'New task'}
)
if response.status_code == 201:
task = response.json()
print('Created:', task['id'])
elif response.status_code == 200:
print('Updated existing resource')
else:
print('Unexpected code:', response.status_code)状态码:4xx 客户端错误
4xx 错误表示您的智能体发送了错误请求。常见的错误包括:
400 Bad Request— JSON 无效或缺少必需字段401 Unauthorized— 缺少或无效的 API 密钥404 Not Found— 资源不存在429 Too Many Requests— 超出速率限制
这些错误要求您的智能体修正请求,而不是盲目重试。
import requests
response = requests.get(
'https://api.example.com/tasks/9999',
headers={'Authorization': 'Bearer YOUR_KEY'}
)
if response.status_code == 401:
print('AUTH ERROR: Check your API key')
elif response.status_code == 404:
print('Task not found')
elif response.status_code == 429:
retry_after = response.headers.get('Retry-After', 60)
print(f'Rate limited. Wait {retry_after}s')
elif response.status_code == 400:
print('Bad request:', response.json().get('error'))状态码:5xx 服务器错误
5xx 错误表示服务器端出了问题——您的智能体没有做错任何事。常见的错误包括:
500 Internal Server Error— 服务器程序错误或崩溃502 Bad Gateway— 上游服务失败503 Service Unavailable— 服务器过载或已停止运行
短暂等待后,可以安全地重试这些请求。
import requests
import time
def get_with_retry(url, headers, max_retries=3):
for attempt in range(max_retries):
response = requests.get(url, headers=headers)
if response.status_code < 500:
return response # success or client error
wait = 2 ** attempt
print(f'Server error {response.status_code}, retrying in {wait}s...')
time.sleep(wait)
return response # return last response after retries请求标头
标头会随每个请求携带元数据。对智能体而言,最重要的标头包括:
Content-Type: application/json— 告诉服务器请求体是 JSONAuthorization: Bearer TOKEN— 对请求进行身份验证Accept: application/json— 告诉服务器您希望返回 JSONUser-Agent— 标识您的客户端(某些 API 要求提供)
import requests
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer sk-proj-abc123xyz',
'Accept': 'application/json',
'User-Agent': 'MyAgent/1.0'
}
response = requests.post(
'https://api.example.com/analyze',
headers=headers,
json={'text': 'Analyze this document'}
)
print(response.json())JSON 请求体与响应体
大多数现代 API 都以 JSON 格式交换数据。发送数据时,在请求中使用 json=payload(它会自动完成序列化并设置标头)。接收数据时,调用 response.json() 将请求体解析为 Python 字典。
访问数据之前,请始终验证预期的键是否存在。
import requests
# Send JSON body
response = requests.post(
'https://api.example.com/summarize',
json={
'content': 'Long article text here...',
'max_length': 150,
'format': 'bullet_points'
}
)
# Parse JSON response
result = response.json()
# Always check keys exist
summary = result.get('summary', 'No summary returned')
tokens_used = result.get('usage', {}).get('total_tokens', 0)
print('Summary:', summary)
print('Tokens used:', tokens_used)整合运用
编写良好的智能体会将 API 调用封装在一个简洁的辅助函数中,统一处理方法选择、正确设置标头、检查状态码和解析 JSON。这样可以让每次 API 交互保持一致,也更容易调试。
请使用 Session 对象复用连接,并在多个请求之间共享标头。
import requests
class APIClient:
def __init__(self, base_url, api_key):
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json',
'Accept': 'application/json'
})
def get(self, path, params=None):
r = self.session.get(f'{self.base_url}{path}', params=params)
r.raise_for_status()
return r.json()
def post(self, path, payload):
r = self.session.post(f'{self.base_url}{path}', json=payload)
r.raise_for_status()
return r.json()
# Usage
client = APIClient('https://api.example.com', 'sk-proj-abc123')
tasks = client.get('/tasks', params={'status': 'open'})
new_task = client.post('/tasks', {'title': 'Write report'})快速检查:HTTP 方法
测试您对 HTTP 方法和状态码的理解。
HTTP 基础回顾
现在,您已经掌握了每个智能体都依赖的 HTTP 基础:
- GET 获取,POST 创建,PUT/PATCH 更新,DELETE 移除
- 2xx = 成功,4xx = 您的智能体出错,5xx = 服务器出错
- 标头携带身份验证信息(
Authorization: Bearer)和格式信息(Content-Type: application/json) - 使用
response.json()解析请求体,使用.get()安全地访问字段 Session对象会在多个请求之间共享标头和连接
掌握这些基础知识后,您就可以放心地将智能体连接到任何 REST API。
常见问题解答
「代理开发者的 REST API 基础」课时是免费的吗?
是的 — 「代理开发者的 REST API 基础」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「代理开发者的 REST API 基础」这节课中我会学到什么?
HTTP 方法、状态码、请求头以及 JSON 请求/响应格式。 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「代理开发者的 REST API 基础」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 代理开发者的 REST API 基础
- 身份验证:API 密钥与 OAuth
- 处理 API 响应与错误
- 速率限制与重试逻辑