Giới thiệu: Tại Sao Kiểm Thử API Lại Quan Trọng?
Xin chào, tôi là một kỹ sư backend đã làm việc với các API AI trong hơn 3 năm. Hôm nay tôi muốn chia sẻ với các bạn một bài hướng dẫn chi tiết nhất về việc kiểm thử chấp nhận API AI — hay còn gọi là Acceptance Testing. Đây là bước cuối cùng và quan trọng nhất trước khi đưa sản phẩm AI vào sản xuất thực tế.
Khi tôi mới bắt đầu, tôi đã từng bỏ qua bước kiểm thử này và phải trả giá bằng những incident nghiêm trọng trong production. Một lần, API trả về định dạng JSON khác với tài liệu, gây crash toàn bộ hệ thống của khách hàng. Kể từ đó, tôi luôn tuân thủ nghiêm ngặt quy trình kiểm thử.
Trong bài viết này, tôi sẽ hướng dẫn bạn từng bước một cách chi tiết, tránh những thuật ngữ phức tạp, để bạn có thể tự tin kiểm thử bất kỳ API AI nào một cách chuyên nghiệp.
1. API là gì? Hiểu Đơn Giản Nhất
API viết tắt của Application Programming Interface
Hãy tưởng tượng bạn đến nhà hàng. Bạn (ứng dụng của bạn) là khách hàng, nhà bếp là hệ thống AI, và người phục vụ là API. Bạn không cần vào bếp để lấy đồ ăn — bạn chỉ cần gọi món qua người phục vụ, và người đó sẽ mang đồ ăn ra cho bạn.
API hoạt động tương tự: bạn gửi yêu cầu (request) với những gì bạn muốn, API sẽ xử lý và trả về kết quả (response).
Request và Response
Một request gồm 3 phần chính:
- Endpoint: Địa chỉ của API (giống như địa chỉ nhà hàng)
- Method: Phương thức gửi — GET (lấy dữ liệu), POST (gửi dữ liệu mới), PUT (cập nhật), DELETE (xóa)
- Headers và Body: Thông tin bổ sung và dữ liệu bạn muốn gửi
Response sẽ có:
- Status Code: Mã trạng thái (200 = thành công, 400 = lỗi request, 500 = lỗi server)
- Headers: Thông tin meta về response
- Body: Dữ liệu trả về (thường là JSON)
2. Chuẩn Bị Môi Trường Kiểm Thử
2.1 Đăng ký tài khoản HolySheep AI
Trước tiên, bạn cần một tài khoản API để thực hành. Tôi đã thử nghiệm nhiều nhà cung cấp và
đăng ký tại đây — HolySheep AI là lựa chọn tối ưu với tỷ giá ¥1=$1 (tiết kiệm 85%+ so với các nhà cung cấp khác), hỗ trợ thanh toán WeChat/Alipay thuận tiện, và độ trễ chỉ dưới 50ms.
Giá 2026 cho các model phổ biến:
- GPT-4.1: $8/MTok
- Claude Sonnet 4.5: $15/MTok
- Gemini 2.5 Flash: $2.50/MTok
- DeepSeek V3.2: $0.42/MTok
2.2 Công cụ cần thiết
Để kiểm thử API, bạn cần:
- Postman hoặc Insomnia (giao diện đồ họa trực quan)
- curl (dòng lệnh, có sẵn trên macOS/Linux)
- Python với thư viện requests (nếu bạn muốn tự động hóa)
Trong bài hướng dẫn này, tôi sẽ sử dụng curl vì nó miễn phí, nhẹ, và hoạt động trên mọi hệ điều hành.
3. Cấu Trúc Cơ Bản Của Một API Request
3.1 Cấu trúc endpoint
Với HolySheep AI, base_url luôn là:
https://api.holysheep.ai/v1
Endpoint cho chat completions:
https://api.holysheep.ai/v1/chat/completions
3.2 Cấu trúc Headers
Headers là các thông tin meta gửi kèm request:
Content-Type: application/json
Authorization: Bearer YOUR_HOLYSHEEP_API_KEY
Lưu ý quan trọng: Thay YOUR_HOLYSHEEP_API_KEY bằng API key thực tế của bạn (khóa này nằm trong dashboard sau khi đăng ký).
4. Test Đầu Tiên: Gửi Request Cơ Bản
4.1 Sử dụng curl (Command Line)
Đây là test đơn giản nhất để xác nhận API hoạt động:
curl -X POST https://api.holysheep.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_HOLYSHEEP_API_KEY" \
-d '{
"model": "gpt-4.1",
"messages": [
{
"role": "user",
"content": "Xin chào, đây là test đầu tiên của tôi!"
}
],
"max_tokens": 50
}'
Giải thích từng phần:
- -X POST: Chỉ định phương thức HTTP là POST
- -H: Headers gửi kèm (Content-Type và Authorization)
- -d: Dữ liệu body gửi đi (JSON)
- model: Chọn model AI bạn muốn sử dụng
- messages: Mảng chứa lịch sử hội thoại
- max_tokens: Giới hạn số token tối đa trong response
4.2 Kiểm tra Response
Nếu thành công, bạn sẽ nhận được response có dạng:
{
"id": "chatcmpl-xxx",
"object": "chat.completion",
"created": 1735689600,
"model": "gpt-4.1",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Xin chào! Tôi là trợ lý AI..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 15,
"completion_tokens": 25,
"total_tokens": 40
}
}
4.3 Sử dụng Python (Script tự động hóa)
Nếu bạn muốn kiểm thử tự động hóa, đây là script Python:
import requests
import json
import time
Cấu hình API
BASE_URL = "https://api.holysheep.ai/v1"
API_KEY = "YOUR_HOLYSHEEP_API_KEY"
def test_api_basic():
"""Test cơ bản: Gửi một message và nhận response"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
payload = {
"model": "gpt-4.1",
"messages": [
{"role": "user", "content": " Xin chào, hãy cho tôi biết thời gian hiện tại"}
],
"max_tokens": 100,
"temperature": 0.7
}
# Gửi request
start_time = time.time()
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload
)
end_time = time.time()
# Xử lý response
latency = (end_time - start_time) * 1000 # Convert sang milliseconds
print(f"Mã trạng thái: {response.status_code}")
print(f"Độ trễ: {latency:.2f}ms")
if response.status_code == 200:
data = response.json()
content = data["choices"][0]["message"]["content"]
print(f"Response: {content}")
return True, latency
else:
print(f"Lỗi: {response.text}")
return False, latency
if __name__ == "__main__":
success, latency = test_api_basic()
print(f"\nKết quả: {'✅ Thành công' if success else '❌ Thất bại'}")
print(f"Độ trễ trung bình: {latency:.2f}ms")
5. Các Trường Hợp Kiểm Thử Cần Thiết
5.1 Test với System Prompt
System prompt giúp định nghĩa cách AI phản hồi:
import requests
API_KEY = "YOUR_HOLYSHEEP_API_KEY"
BASE_URL = "https://api.holysheep.ai/v1"
def test_system_prompt():
"""Test với system prompt để định hướng AI"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
payload = {
"model": "claude-sonnet-4.5",
"messages": [
{
"role": "system",
"content": "Bạn là một chuyên gia Python với 10 năm kinh nghiệm.
Trả lời ngắn gọn, có code mẫu."
},
{
"role": "user",
"content": "Giải thích vòng lặp for trong Python"
}
],
"max_tokens": 200
}
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload
)
if response.status_code == 200:
data = response.json()
print("✅ Test system prompt thành công!")
print(f"Response: {data['choices'][0]['message']['content']}")
else:
print(f"❌ Lỗi: {response.status_code} - {response.text}")
test_system_prompt()
5.2 Test Multi-turn Conversation (Hội thoại nhiều lượt)
def test_multi_turn_conversation():
"""Test hội thoại liên tục, AI nhớ ngữ cảnh"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
# Hội thoại 3 lượt
messages = [
{"role": "user", "content": "Tôi tên là Minh"},
{"role": "assistant", "content": "Xin chào Minh! Rất vui được gặp bạn."},
{"role": "user", "content": "Tôi thích lập trình Python"},
{"role": "assistant", "content": "Python là ngôn ngữ tuyệt vời! Bạn đang làm project gì?"},
{"role": "user", "content": "Tên tôi là gì?"} # AI cần nhớ từ lượt đầu
]
payload = {
"model": "gpt-4.1",
"messages": messages,
"max_tokens": 100
}
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload
)
if response.status_code == 200:
data = response.json()
answer = data["choices"][0]["message"]["content"]
print(f"✅ Hội thoại hoạt động!")
print(f"AI trả lời: {answer}")
# Kiểm tra AI có nhớ tên không
if "Minh" in answer:
print("✅ AI nhớ được ngữ cảnh!")
else:
print("⚠️ AI không nhớ được ngữ cảnh")
test_multi_turn_conversation()
5.3 Test Streaming Response
Streaming cho phép nhận response theo từng phần, tốt cho ứng dụng chatbot:
import requests
import json
def test_streaming():
"""Test streaming response - nhận từng phần một"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
payload = {
"model": "gpt-4.1",
"messages": [
{"role": "user", "content": "Đếm từ 1 đến 5"}
],
"max_tokens": 100,
"stream": True # Bật streaming
}
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload,
stream=True
)
print("🔄 Đang nhận streaming response...")
full_content = ""
for line in response.iter_lines():
if line:
# Server-Sent Events format
line_text = line.decode('utf-8')
if line_text.startswith('data: '):
data_str = line_text[6:] # Bỏ "data: "
if data_str == "[DONE]":
break
try:
data = json.loads(data_str)
if 'choices' in data and len(data['choices']) > 0:
delta = data['choices'][0].get('delta', {})
if 'content' in delta:
content = delta['content']
print(content, end='', flush=True)
full_content += content
except json.JSONDecodeError:
continue
print(f"\n✅ Streaming hoàn tất! Tổng: {full_content}")
test_streaming()
6. Đo Lường Hiệu Suất (Performance Testing)
6.1 Test độ trễ (Latency)
Độ trễ là thời gian từ lúc gửi request đến khi nhận đầy đủ response. HolySheep AI cam kết dưới 50ms:
import requests
import statistics
API_KEY = "YOUR_HOLYSHEEP_API_KEY"
BASE_URL = "https://api.holysheep.ai/v1"
def test_latency(iterations=10):
"""Đo độ trễ trung bình qua nhiều request"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
payload = {
"model": "gpt-4.1",
"messages": [{"role": "user", "content": "Chào bạn"}],
"max_tokens": 50
}
latencies = []
print(f"Đang đo độ trễ qua {iterations} request...")
for i in range(iterations):
import time
start = time.time()
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload
)
end = time.time()
latency_ms = (end - start) * 1000
latencies.append(latency_ms)
print(f" Request {i+1}: {latency_ms:.2f}ms")
print("\n📊 Kết quả:")
print(f" Trung bình: {statistics.mean(latencies):.2f}ms")
print(f" Trung vị: {statistics.median(latencies):.2f}ms")
print(f" Min: {min(latencies):.2f}ms")
print(f" Max: {max(latencies):.2f}ms")
avg = statistics.mean(latencies)
if avg < 50:
print(f" ✅ Đạt cam kết <50ms!")
else:
print(f" ⚠️ Vượt ngưỡng 50ms")
test_latency(5)
6.2 Test throughput (Số request đồng thời)
import requests
import concurrent.futures
import time
def test_concurrent_requests(num_requests=10):
"""Test xử lý nhiều request đồng thời"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
payload = {
"model": "gpt-4.1",
"messages": [{"role": "user", "content": "Test đồng thời"}],
"max_tokens": 20
}
def send_request(i):
start = time.time()
try:
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload,
timeout=30
)
elapsed = time.time() - start
return {"success": True, "time": elapsed, "status": response.status_code}
except Exception as e:
return {"success": False, "error": str(e)}
print(f"Đang gửi {num_requests} request đồng thời...")
start_total = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(send_request, range(num_requests)))
total_time = time.time() - start_total
success_count = sum(1 for r in results if r.get("success"))
print(f"\n📊 Kết quả:")
print(f" Tổng thời gian: {total_time:.2f}s")
print(f" Request thành công: {success_count}/{num_requests}")
print(f" Throughput: {num_requests/total_time:.2f} req/s")
test_concurrent_requests(10)
7. Validation và Error Handling
7.1 Kiểm tra response structure
def validate_response(response_data):
"""Validate cấu trúc response có đúng format không"""
required_fields = ["id", "object", "created", "model", "choices", "usage"]
missing_fields = []
for field in required_fields:
if field not in response_data:
missing_fields.append(field)
if missing_fields:
return False, f"Thiếu fields: {missing_fields}"
# Kiểm tra choices
if not response_data["choices"] or len(response_data["choices"]) == 0:
return False, "Choices rỗng"
# Kiểm tra message structure
choice = response_data["choices"][0]
if "message" not in choice:
return False, "Thiếu message trong choice"
message = choice["message"]
if "role" not in message or "content" not in message:
return False, "Thiếu role hoặc content trong message"
# Kiểm tra usage stats
usage = response_data.get("usage", {})
if not all(k in usage for k in ["prompt_tokens", "completion_tokens", "total_tokens"]):
return False, "Thiếu usage stats"
return True, "Response hợp lệ"
def test_validation():
"""Test validation function"""
# Response mẫu
valid_response = {
"id": "test-123",
"object": "chat.completion",
"created": 1234567890,
"model": "gpt-4.1",
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": "Test"},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 5,
"total_tokens": 15
}
}
valid, msg = validate_response(valid_response)
print(f"Response hợp lệ: {valid} - {msg}")
test_validation()
7.2 Xử lý lỗi HTTP
import requests
def handle_api_errors(response):
"""Xử lý các mã lỗi HTTP phổ biến"""
status = response.status_code
error_messages = {
400: "Bad Request - Request không hợp lệ (thiếu trường, sai format)",
401: "Unauthorized - API key không đúng hoặc đã hết hạn",
403: "Forbidden - Không có quyền truy cập resource này",
404: "Not Found - Endpoint không tồn tại",
429: "Too Many Requests - Đã vượt giới hạn rate limit",
500: "Internal Server Error - Lỗi phía server",
503: "Service Unavailable - Server đang bảo trì"
}
if status == 200:
return "✅ Thành công", None
error_msg = error_messages.get(status, f"Lỗi không xác định: {status}")
# Parse error details từ response
try:
error_data = response.json()
details = error_data.get("error", {}).get("message", response.text)
except:
details = response.text
return f"❌ {error_msg}", details
def test_error_handling():
"""Test xử lý lỗi với API key sai"""
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer INVALID_KEY"
}
payload = {
"model": "gpt-4.1",
"messages": [{"role": "user", "content": "Test"}],
"max_tokens": 10
}
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload
)
msg, details = handle_api_errors(response)
print(msg)
if details:
print(f"Chi tiết: {details}")
test_error_handling()
Lỗi thường gặp và cách khắc phục
1. Lỗi 401 Unauthorized - API Key không hợp lệ
Nguyên nhân: API key sai, thiếu, hoặc đã bị thu hồi.
Cách khắc phục:
# Sai: Có khoảng trắng thừa trong Bearer token
"Bearer YOUR_HOLYSHEEP_API_KEY " # ❌ Có space
Đúng: Bearer token chính xác
f"Bearer {API_KEY}" # ✅ Không có khoảng trắng
Kiểm tra API key
import requests
API_KEY = "YOUR_HOLYSHEEP_API_KEY"
response = requests.get(
"https://api.holysheep.ai/v1/models",
headers={"Authorization": f"Bearer {API_KEY}"}
)
print(response.json())
2. Lỗi 400 Bad Request - Request Body không hợp lệ
Nguyên nhân: JSON sai format, thiếu trường bắt buộc, hoặc giá trị không hợp lệ.
Cách khắc phục:
# Sai: Thiếu trường "model" hoặc "messages"
payload = {"content": "Hello"} # ❌ Thiếu model và messages
Đúng: Đầy đủ các trường bắt buộc
payload = {
"model": "gpt-4.1", # ✅ Model bắt buộc
"messages": [ # ✅ Messages bắt buộc
{"role": "user", "content": "Hello"}
]
}
Validate JSON trước khi gửi
import json
try:
json_obj = json.loads(json.dumps(payload))
print("✅ JSON hợp lệ")
except Exception as e:
print(f"❌ JSON lỗi: {e}")
3. Lỗi 429 Rate Limit - Vượt quá giới hạn request
Nguyên nhân: Gửi quá nhiều request trong thời gian ngắn.
Cách khắc phục:
import time
import requests
def retry_with_backoff(max_retries=3, initial_delay=1):
"""Thử lại request với exponential backoff"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
payload = {
"model": "gpt-4.1",
"messages": [{"role": "user", "content": "Test"}],
"max_tokens": 50
}
for attempt in range(max_retries):
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload
)
if response.status_code != 429:
return response
# Exponential backoff
delay = initial_delay * (2 ** attempt)
print(f"Rate limited! Chờ {delay}s trước khi thử lại...")
time.sleep(delay)
return response # Trả về response cuối cùng
Sử dụng
result = retry_with_backoff()
print(f"Status: {result.status_code}")
4. Lỗi Connection Timeout - Không kết nối được server
Nguyên nhân: Network issue, server down, hoặc firewall block.
Cách khắc phục:
# Thêm timeout cho request
import requests
try:
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload,
timeout=30 # ✅ Timeout 30 giây
)
except requests.exceptions.Timeout:
print("❌ Request timeout - Server phản hồi chậm")
except requests.exceptions.ConnectionError:
print("❌ Connection Error - Kiểm tra network")
except requests.exceptions.RequestException as e:
print(f"❌ Lỗi khác: {e}")
5. Lỗi Streaming - Nhận dữ liệu không liên tục
Nguyên nhân: Xử lý streaming không đúng cách, hoặc network instability.
Cách khắc phục:
import requests
import json
def stream_with_error_handling():
"""Streaming với xử lý lỗi tốt"""
payload = {
"model": "gpt-4.1",
"messages": [{"role": "user", "content": "Kể một câu chuyện ngắn"}],
"stream": True
}
try:
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload,
stream=True,
timeout=60
)
if response.status_code != 200:
print(f"❌ Lỗi: {response.status_code}")
return
for line in response.iter_lines():
if line:
line_text = line.decode('utf-8')
if line_text.startswith('data: '):
data_str = line_text[6:]
if data_str == "[DONE]":
break
try:
data = json.loads(data_str)
# Xử lý data...
except json.JSONDecodeError:
continue # Bỏ qua dòng lỗi
except requests.exceptions.Timeout:
print("❌ Streaming timeout")
except Exception as e:
print(f"❌ Lỗi streaming: {e}")
stream_with_error_handling()
Checklist Kiểm Thử Trước Khi Deploy
Trước khi đưa API vào production, hãy đảm bảo hoàn thành checklist sau:
- ✅ Test với API key production (không phải test key)
- ✅ Test tất cả các model bạn sử dụng
- ✅ Test response time đạt yêu cầu (<50ms với HolySheep)
- ✅ Test error handling cho tất cả HTTP status codes
- ✅ Test với dữ liệu edge cases (input rỗng, input quá dài)
- ✅ Test concurrent requests (nhiều user cùng lúc)
- ✅ Test retry mechanism khi API fail
- ✅ Validate response structure trước khi parse
- ✅ Test rate limiting không crash ứng dụng
- ✅ Monitor chi phí sử dụng (đặt budget alerts)
Kết Luận
Kiểm thử API là bước không thể bỏ qua trong quy trình phát triển sản phẩm AI. Qua bài hướng dẫn này, tôi đã chia sẻ những kinh nghiệm thực chiến từ các project thực tế của mình, giúp bạn:
- Hiểu cấu trúc cơ bản của API và cách gửi request
- Sử dụng curl và Python để kiểm thử tự động
- Đo lườ
Tài nguyên liên quan
Bài viết liên quan