RESTful API Testing and Debugging

Using Tools to Test API

1. Postman Testing

Postman is the most popular API testing tool, like a "playground" for APIs.

Postman official website:https://www.postman.com/。

Basic Test Steps:

  1. Create a new request
  2. Set HTTP method (GET, POST, etc.)
  3. Enter API URL
  4. Add request headers and request body
  5. Send request and view response

Postman collection example:

{
  "info": {
    "name": "用户管理 API 测试",
    "description": "测试用户相关的所有 API 端点"
  },
  "item": [
    {
      "name": "获取用户列表",
      "request": {
        "method": "GET",
        "header": [],
        "url": {
          "raw": "{{baseUrl}}/api/users?page=1&limit=10",
          "host": ["{{baseUrl}}"],
          "path": ["api", "users"],
          "query": [
            {"key": "page", "value": "1"},
            {"key": "limit", "value": "10"}
          ]
        }
      }
    }
  ]
}

2. curl Command Line Testing

# 获取用户列表
curl -X GET "https://api.example.com/users" \
     -H "Content-Type: application/json"

# 创建新用户
curl -X POST "https://api.example.com/users" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "张三",
       "email": "zhangsan@example.com"
     }'

# 更新用户信息
curl -X PUT "https://api.example.com/users/123" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "李四",
       "email": "lisi@example.com"
     }'

# 删除用户
curl -X DELETE "https://api.example.com/users/123" \
     -H "Content-Type: application/json"

3. Browser Developer Tools

// 在浏览器控制台中测试
fetch('/api/users', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Debugging Common Issues

1. CORS Cross-Origin Issues

Error message:

Access to fetch at 'https://api.example.com/users' from origin 'http://localhost:3000' 
has been blocked by CORS policy

Solution:

// 服务器端需要设置 CORS 头
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});

2. Status Code Errors

Common errors and causes:

Status Code Possible Cause Solution
400 Request data format error Check JSON format and required fields
401 Authentication failed Check whether the Token is correct
404 API path error Confirm the URL is spelled correctly
500 Internal server error Check server logs

3. Data Format Issues

// 错误的请求格式
{
  name: "张三",  // ❌ 缺少引号
  'email': "test@example.com",  // ❌ 单引号
  age: "25"  // ❌ 数字用了字符串
}

// 正确的请求格式
{
  "name": "张三",  // ✅ 双引号
  "email": "test@example.com",  // ✅ 双引号
  "age": 25  // ✅ 数字类型
}

Automated Testing

Unit Test Example

Example

// Use the Jest testing framework
describe('User API Test', () => {
  test('should be able to get the user list', async () => {
    const response = await fetch('/api/users');
    const data = await response.json();
   
    expect(response.status).toBe(200);
    expect(data.success).toBe(true);
    expect(Array.isArray(data.data)).toBe(true);
  });
 
  test('should be able to create a new user', async () => {
    const newUser = {
      name: "Test User",
      email: "test@example.com"
    };
   
    const response = await fetch('/api/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(newUser)
    });
   
    const data = await response.json();
   
    expect(response.status).toBe(201);
    expect(data.success).toBe(true);
    expect(data.data.name).toBe(newUser.name);
  });
});
Other Extensions