api-tester
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Tester
API测试工具
Overview
概述
Test API endpoints by sending HTTP requests, validating responses, and reporting results. Supports REST and GraphQL APIs with authentication, custom headers, request bodies, and structured assertions on status codes, headers, and response payloads.
通过发送HTTP请求、验证响应并生成报告来测试API端点。支持REST与GraphQL API,包含认证、自定义请求头、请求体功能,以及对状态码、请求头和响应负载的结构化断言。
Instructions
操作步骤
When a user asks you to test or debug an API endpoint, follow these steps:
当用户要求你测试或调试API端点时,请遵循以下步骤:
Step 1: Gather endpoint details
步骤1:收集端点详情
Determine from the user or codebase:
- URL: The full endpoint URL
- Method: GET, POST, PUT, PATCH, DELETE
- Headers: Content-Type, Authorization, custom headers
- Body: JSON payload, form data, or query parameters
- Auth: Bearer token, API key, basic auth
- Expected response: Status code, response shape, specific values
从用户或代码库中确认以下信息:
- URL:完整的端点URL
- Method:GET、POST、PUT、PATCH、DELETE
- Headers:Content-Type、Authorization、自定义请求头
- Body:JSON负载、表单数据或查询参数
- Auth:Bearer令牌、API密钥、基础认证
- Expected response:状态码、响应结构、特定值
Step 2: Send the request
步骤2:发送请求
Using curl (preferred for quick tests):
bash
undefined使用curl(快速测试首选):
bash
undefinedGET request
GET request
curl -s -w "\nHTTP Status: %{http_code}\nTime: %{time_total}s\n"
-H "Authorization: Bearer $TOKEN"
"https://api.example.com/users?page=1"
-H "Authorization: Bearer $TOKEN"
"https://api.example.com/users?page=1"
curl -s -w "\nHTTP Status: %{http_code}\nTime: %{time_total}s\n"
-H "Authorization: Bearer $TOKEN"
"https://api.example.com/users?page=1"
-H "Authorization: Bearer $TOKEN"
"https://api.example.com/users?page=1"
POST request with JSON
POST request with JSON
curl -s -w "\nHTTP Status: %{http_code}\nTime: %{time_total}s\n"
-X POST
-H "Content-Type: application/json"
-H "Authorization: Bearer $TOKEN"
-d '{"name": "Jane", "email": "jane@example.com"}'
"https://api.example.com/users"
-X POST
-H "Content-Type: application/json"
-H "Authorization: Bearer $TOKEN"
-d '{"name": "Jane", "email": "jane@example.com"}'
"https://api.example.com/users"
**Using Python (for complex flows):**
```python
import requests
import json
import time
def test_endpoint(method, url, headers=None, body=None, expected_status=200):
start = time.time()
response = requests.request(method, url, headers=headers, json=body, timeout=30)
elapsed = time.time() - start
result = {
"status": response.status_code,
"time_ms": round(elapsed * 1000),
"headers": dict(response.headers),
"body": response.json() if response.headers.get("content-type", "").startswith("application/json") else response.text,
}
passed = response.status_code == expected_status
print(f"{'PASS' if passed else 'FAIL'} | {method} {url} | {response.status_code} | {result['time_ms']}ms")
return result, passedcurl -s -w "\nHTTP Status: %{http_code}\nTime: %{time_total}s\n"
-X POST
-H "Content-Type: application/json"
-H "Authorization: Bearer $TOKEN"
-d '{"name": "Jane", "email": "jane@example.com"}'
"https://api.example.com/users"
-X POST
-H "Content-Type: application/json"
-H "Authorization: Bearer $TOKEN"
-d '{"name": "Jane", "email": "jane@example.com"}'
"https://api.example.com/users"
**使用Python(适用于复杂流程):**
```python
import requests
import json
import time
def test_endpoint(method, url, headers=None, body=None, expected_status=200):
start = time.time()
response = requests.request(method, url, headers=headers, json=body, timeout=30)
elapsed = time.time() - start
result = {
"status": response.status_code,
"time_ms": round(elapsed * 1000),
"headers": dict(response.headers),
"body": response.json() if response.headers.get("content-type", "").startswith("application/json") else response.text,
}
passed = response.status_code == expected_status
print(f"{'PASS' if passed else 'FAIL'} | {method} {url} | {response.status_code} | {result['time_ms']}ms")
return result, passedStep 3: Validate the response
步骤3:验证响应
Check these in order:
- Status code matches expected (200, 201, 204, 400, 401, 404, etc.)
- Response time is acceptable (flag if > 2 seconds)
- Content-Type header matches expected format
- Response body structure matches expected schema
- Specific values match assertions
python
def validate_response(result, assertions):
failures = []
body = result["body"]
for field, expected in assertions.items():
actual = body
for key in field.split("."):
if isinstance(actual, dict):
actual = actual.get(key)
elif isinstance(actual, list) and key.isdigit():
actual = actual[int(key)]
else:
actual = None
break
if actual != expected:
failures.append(f" {field}: expected {expected!r}, got {actual!r}")
return failures按以下顺序检查:
- 状态码是否与预期值匹配(200、201、204、400、401、404等)
- 响应时间是否在可接受范围内(若超过2秒则标记为缓慢)
- Content-Type请求头是否与预期格式匹配
- 响应体结构是否符合预期 schema
- 特定值是否与断言一致
python
def validate_response(result, assertions):
failures = []
body = result["body"]
for field, expected in assertions.items():
actual = body
for key in field.split("."):
if isinstance(actual, dict):
actual = actual.get(key)
elif isinstance(actual, list) and key.isdigit():
actual = actual[int(key)]
else:
actual = None
break
if actual != expected:
failures.append(f" {field}: expected {expected!r}, got {actual!r}")
return failuresStep 4: Report results
步骤4:报告结果
Format as a clear test report:
API Test Results
================
Endpoint: POST /api/users
Status: 201 Created (expected 201) -- PASS
Time: 142ms
Body: Valid JSON, 3 fields
Assertions:
[PASS] body.id is present
[PASS] body.name == "Jane"
[PASS] body.email == "jane@example.com"
[FAIL] body.role expected "admin", got "user"
Result: 3/4 assertions passed整理为清晰的测试报告格式:
API Test Results
================
Endpoint: POST /api/users
Status: 201 Created (expected 201) -- PASS
Time: 142ms
Body: Valid JSON, 3 fields
Assertions:
[PASS] body.id is present
[PASS] body.name == "Jane"
[PASS] body.email == "jane@example.com"
[FAIL] body.role expected "admin", got "user"
Result: 3/4 assertions passedExamples
示例
Example 1: Test a CRUD flow
示例1:测试CRUD流程
User request: "Test the users API -- create, read, update, delete"
Output:
API Test Suite: Users CRUD
==========================
1. POST /api/users
Status: 201 Created -- PASS
Time: 156ms
Body: {"id": 42, "name": "Test User", "email": "test@example.com"}
2. GET /api/users/42
Status: 200 OK -- PASS
Time: 38ms
Body: {"id": 42, "name": "Test User", "email": "test@example.com"}
3. PUT /api/users/42
Status: 200 OK -- PASS
Time: 89ms
Body: {"id": 42, "name": "Updated Name", "email": "test@example.com"}
4. DELETE /api/users/42
Status: 204 No Content -- PASS
Time: 45ms
5. GET /api/users/42 (verify deletion)
Status: 404 Not Found -- PASS
Time: 22ms
Result: 5/5 PASSED用户请求: "Test the users API -- create, read, update, delete"
输出:
API Test Suite: Users CRUD
==========================
1. POST /api/users
Status: 201 Created -- PASS
Time: 156ms
Body: {"id": 42, "name": "Test User", "email": "test@example.com"}
2. GET /api/users/42
Status: 200 OK -- PASS
Time: 38ms
Body: {"id": 42, "name": "Test User", "email": "test@example.com"}
3. PUT /api/users/42
Status: 200 OK -- PASS
Time: 89ms
Body: {"id": 42, "name": "Updated Name", "email": "test@example.com"}
4. DELETE /api/users/42
Status: 204 No Content -- PASS
Time: 45ms
5. GET /api/users/42 (verify deletion)
Status: 404 Not Found -- PASS
Time: 22ms
Result: 5/5 PASSEDExample 2: Debug a failing request
示例2:调试失败的请求
User request: "I'm getting a 401 on POST /api/orders, can you figure out why?"
Output:
Debugging POST /api/orders
===========================
Test 1: No auth header
Status: 401 -- Missing Authorization header (expected)
Test 2: With Bearer token
Status: 401 -- Response: {"error": "Token expired"}
Note: Token exp claim is 2024-01-15T00:00:00Z (expired)
Test 3: With refreshed token
Status: 201 Created -- PASS
Root cause: Your Bearer token has expired.
Fix: Refresh the token using POST /api/auth/refresh用户请求: "I'm getting a 401 on POST /api/orders, can you figure out why?"
输出:
Debugging POST /api/orders
===========================
Test 1: No auth header
Status: 401 -- Missing Authorization header (expected)
Test 2: With Bearer token
Status: 401 -- Response: {"error": "Token expired"}
Note: Token exp claim is 2024-01-15T00:00:00Z (expired)
Test 3: With refreshed token
Status: 201 Created -- PASS
Root cause: Your Bearer token has expired.
Fix: Refresh the token using POST /api/auth/refreshGuidelines
注意事项
- Never send requests to production APIs unless the user explicitly confirms. Ask first.
- Mask sensitive values (tokens, passwords, API keys) in output. Show only the last 4 characters.
- For sequences of dependent requests (create then read), use the response from the first request to build the second.
- Include response time in reports. Flag responses over 2 seconds as slow.
- When testing auth flows, test both the happy path and common failure modes (expired token, wrong credentials, missing permissions).
- For GraphQL, use POST with the query in the JSON body and validate the field separately from
data.errors - If an endpoint returns pagination, test the first page and mention the total count.
- Always set a timeout (30 seconds) to avoid hanging on unresponsive endpoints.
- 除非用户明确确认,否则绝不要向生产环境API发送请求。先询问用户。
- 在输出中屏蔽敏感值(令牌、密码、API密钥),仅显示最后4位字符。
- 对于依赖型请求序列(如创建后查询),使用第一个请求的响应数据构建第二个请求。
- 报告中需包含响应时间,将超过2秒的响应标记为缓慢。
- 测试认证流程时,需同时测试正常流程和常见失败场景(过期令牌、错误凭证、权限不足)。
- 对于GraphQL,使用POST方法,将查询放在JSON请求体中,并分别验证字段和
data字段。errors - 若端点支持分页,需测试第一页并提及总数据量。
- 始终设置超时时间(30秒),避免因端点无响应导致程序挂起。