本文目录导读:

- 使用 Python + requests(最常用)
- 使用 JavaScript/Node.js + axios
- 测试框架版(pytest + requests)
- 完整的测试工具类
- 使用 curl 命令行测试
- 推荐的最佳实践
我来帮你编写接口请求测试脚本,包含常用的几种方式:
使用 Python + requests(最常用)
基础示例
import requests
import json
# GET 请求
def test_get():
url = "https://api.example.com/users"
headers = {
"Authorization": "Bearer your_token",
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
print(f"状态码: {response.status_code}")
print(f"响应内容: {response.text}")
print(f"JSON数据: {response.json()}")
# 断言
assert response.status_code == 200
assert response.json()["code"] == 0
# POST 请求
def test_post():
url = "https://api.example.com/login"
data = {
"username": "admin",
"password": "123456"
}
response = requests.post(url, json=data)
result = response.json()
print(result)
assert result["message"] == "success"
# 带参数的请求
def test_with_params():
url = "https://api.example.com/search"
params = {
"keyword": "python",
"page": 1,
"size": 10
}
response = requests.get(url, params=params)
return response.json()
使用 JavaScript/Node.js + axios
const axios = require('axios');
// GET 请求
async function testGet() {
try {
const response = await axios.get('https://api.example.com/users', {
headers: {
'Authorization': 'Bearer your_token'
},
params: {
page: 1,
limit: 10
}
});
console.log('状态码:', response.status);
console.log('数据:', response.data);
} catch (error) {
console.error('请求失败:', error.message);
}
}
// POST 请求
async function testPost() {
try {
const response = await axios.post('https://api.example.com/login', {
username: 'admin',
password: '123456'
});
console.log(response.data);
} catch (error) {
console.error(error.response.data);
}
}
测试框架版(pytest + requests)
import pytest
import requests
class TestAPI:
base_url = "https://api.example.com"
def setup_method(self):
# 测试前置
self.session = requests.Session()
self.session.headers.update({
"Content-Type": "application/json"
})
def test_login_success(self):
"""测试登录成功"""
url = f"{self.base_url}/login"
data = {
"username": "admin",
"password": "123456"
}
response = self.session.post(url, json=data)
result = response.json()
assert response.status_code == 200
assert result["code"] == 0
assert "token" in result["data"]
# 保存token供后续使用
self.token = result["data"]["token"]
def test_get_user_info(self):
"""测试获取用户信息"""
url = f"{self.base_url}/user/info"
headers = {"Authorization": f"Bearer {self.token}"}
response = self.session.get(url, headers=headers)
assert response.status_code == 200
user_info = response.json()
assert user_info["username"] == "admin"
def test_create_user(self):
"""测试创建用户"""
url = f"{self.base_url}/users"
data = {
"name": "new_user",
"email": "new@example.com"
}
response = self.session.post(url, json=data)
assert response.status_code == 201
assert response.json()["id"] > 0
def test_file_upload(self):
"""测试文件上传"""
url = f"{self.base_url}/upload"
files = {
"file": ("test.txt", "Hello World", "text/plain")
}
response = self.session.post(url, files=files)
assert response.status_code == 200
# 运行测试
if __name__ == "__main__":
pytest.main(["-v", "-s", "test_api.py"])
完整的测试工具类
import requests
import json
import logging
from typing import Dict, Any
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class APITestClient:
def __init__(self, base_url: str, token: str = None):
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
"Content-Type": "application/json"
})
if token:
self.session.headers.update({
"Authorization": f"Bearer {token}"
})
def request(self, method: str, endpoint: str,
data: Dict = None, params: Dict = None,
headers: Dict = None, files: Dict = None) -> Dict:
"""统一的请求方法"""
url = f"{self.base_url}{endpoint}"
logger.info(f"请求: {method} {url}")
logger.info(f"参数: {data or params}")
try:
response = self.session.request(
method=method,
url=url,
json=data,
params=params,
headers=headers,
files=files,
timeout=30
)
logger.info(f"状态码: {response.status_code}")
logger.info(f"响应: {response.text[:200]}...")
return {
"status_code": response.status_code,
"headers": dict(response.headers),
"data": response.json() if response.text else {}
}
except requests.exceptions.RequestException as e:
logger.error(f"请求失败: {e}")
return {"error": str(e)}
def get(self, endpoint: str, **kwargs) -> Dict:
return self.request("GET", endpoint, **kwargs)
def post(self, endpoint: str, **kwargs) -> Dict:
return self.request("POST", endpoint, **kwargs)
def put(self, endpoint: str, **kwargs) -> Dict:
return self.request("PUT", endpoint, **kwargs)
def delete(self, endpoint: str, **kwargs) -> Dict:
return self.request("DELETE", endpoint, **kwargs)
# 使用示例
if __name__ == "__main__":
# 初始化客户端
client = APITestClient("https://api.example.com")
# 登录
login_result = client.post("/login", data={
"username": "admin",
"password": "123456"
})
if login_result["status_code"] == 200:
token = login_result["data"]["token"]
print(f"获取到token: {token}")
else:
print(f"登录失败: {login_result}")
使用 curl 命令行测试
# GET 请求
curl -X GET 'https://api.example.com/users' \
-H 'Authorization: Bearer your-token' \
-H 'Content-Type: application/json'
# POST 请求
curl -X POST 'https://api.example.com/login' \
-H 'Content-Type: application/json' \
-d '{"username":"admin","password":"123456"}'
# 带参数的 GET 请求
curl -X GET 'https://api.example.com/search?keyword=python&page=1' \
-H 'Authorization: Bearer your-token'
# 文件上传
curl -X POST 'https://api.example.com/upload' \
-F 'file=@test.txt'
推荐的最佳实践
- 错误处理:始终添加异常处理
- 日志记录:记录请求和响应信息
- 参数配置:使用配置文件管理URL、token等
- 断言验证:对响应状态码和内容做验证
- 数据清理:测试完成后清理测试数据
需要哪种方式的更详细示例?
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播