RESTful API テストとデバッグ

ツールを使用してAPIをテストする

1. Postman テスト

Postman は最も人気のあるAPIテストツールで、APIの「実験場」のようなものです。

Postman 公式サイトのアドレス:https://www.postman.com/。

基本的なテスト手順:

  1. 新しいリクエストを作成
  2. HTTPメソッドを設定(GET、POSTなど)
  3. APIアドレスを入力
  4. リクエストヘッダーとリクエストボディを追加
  5. リクエストを送信してレスポンスを確認

Postman コレクションの例:

{
  "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 コマンドラインテスト

# 获取用户列表
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. ブラウザの開発者ツール

// 在浏览器控制台中测试
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));

よくある問題のデバッグ

1. CORS クロスオリジン問題

エラーメッセージ:

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

解決策:

// 服务器端需要设置 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. ステータスコードエラー

よくあるエラーと原因:

ステータスコード 考えられる原因 解決方法
400 リクエストデータの形式エラー JSON形式と必須フィールドを確認
401 認証失敗 Tokenが正しいか確認
404 APIパスのエラー URLのスペルが正しいか確認
500 サーバー内部エラー サーバーログを確認

3. データ形式の問題

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

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

自動化テスト

単体テストの例

例

// Jest テストフレームワークを使用
describe('ユーザーAPIテスト', () => {
  test('ユーザーリストを取得できるはず', 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('新しいユーザーを作成できるはず', async () => {
    const newUser = {
      name: "テストユーザー",
      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);
  });
});
その他の拡張