DEV Community

Cover image for API構築を自動化!5つのAIエージェントで仕様書作成からテストまで
Akira
Akira

Posted on • Originally published at apidog.com

API構築を自動化!5つのAIエージェントで仕様書作成からテストまで

あらゆる用途に1つの汎用AIアシスタントを使うのはやめましょう。専門分野ごとに5つのエージェントを設定し、実践的にAPIを構築していきます。バックエンドアーキテクトがシステム設計、データベースオプティマイザーがスキーマレビュー、フロントエンドデベロッパーがクライアント実装、コードレビュアーがセキュリティ監査、リアリティチェッカーが出荷前検証を担当します。

Apidog を今すぐ試す

迅速なAPI構築を目指す際、1つのAIアシスタントに全作業を任せるのは非効率です。たとえば、1つのAIだけでデータベース設計・エンドポイント作成・フロントエンド構築・コードレビュー・テストまで担わせると、インデックス不足や脆弱なエンドポイント、エラー無視のフロントエンド、曖昧なテストなど品質問題が起こります。

専門エージェントごとに担当領域を明確化すれば、各工程でチェックリストに基づいた成果物を生成できます。バックエンドアーキテクトは拡張性、データベースオプティマイザーはインデックス、コードレビュアーは脆弱性、リアリティチェッカーは証拠付き検証を担保します。

このガイドでは、The Agencyコレクションから5つのエージェントを導入し、API構築ワークフローを実践します。APIのテスト・ドキュメント化には Apidog を使い、OpenAPI仕様に基づいた検証まで自動化します。

使用する5つのエージェント

エージェント 部門 責任
Backend Architect (バックエンドアーキテクト) Engineering (エンジニアリング) API設計、データベーススキーマ、認証
Database Optimizer (データベースオプティマイザー) Engineering (エンジニアリング) インデックス推奨、クエリ最適化
Frontend Developer (フロントエンドデベロッパー) Engineering (エンジニアリング) Reactコンポーネント、APIクライアント、状態管理
Code Reviewer (コードレビュアー) Engineering (エンジニアリング) セキュリティ監査、型安全性、エラー処理
Reality Checker (リアリティチェッカー) Testing (テスト) 証拠に基づく検証、スクリーンショット証明

エージェントのインストール

# The Agencyリポジトリをクローン
git clone https://github.com/msitarzewski/agency-agents.git
cd agency-agents

# エージェントをClaude Codeにコピー
cp engineering/engineering-backend-architect.md ~/.claude/agents/
cp engineering/engineering-database-optimizer.md ~/.claude/agents/
cp engineering/engineering-frontend-developer.md ~/.claude/agents/
cp engineering/engineering-code-reviewer.md ~/.claude/agents/
cp testing/testing-reality-checker.md ~/.claude/agents/
Enter fullscreen mode Exit fullscreen mode

ステップ1: バックエンドアーキテクトでAPIシステム設計

新しいClaude Codeセッションで以下のプロンプトを入力:

Activate Backend Architect mode. (バックエンドアーキテクトモードをアクティブ化)

Design a REST API for an e-commerce platform with:
- User authentication (JWT with refresh tokens)
- Product catalog with categories and filtering
- Shopping cart management
- Order processing with status tracking
- Payment webhook integration

Output:
1. OpenAPI 3.0 specification
2. PostgreSQL database schema with relationships
3. Project folder structure (Express.js + TypeScript)
4. Authentication flow diagram
Enter fullscreen mode Exit fullscreen mode

期待される成果物

  • OpenAPI仕様(一部例):
openapi: 3.0.0
info:
  title: "E-commerce API"
  version: 1.0.0
paths:
  /auth/login:
    post:
      summary: User login
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                email: { type: string, format: email }
                password: { type: string, minLength: 8 }
      responses:
        '200':
          description: "JWT tokens"
          content:
            application/json:
              schema:
                type: object
                properties:
                  accessToken: { type: string }
                  refreshToken: { type: string }
Enter fullscreen mode Exit fullscreen mode
  • データベーススキーマ例:
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE products (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2) NOT NULL CHECK (price >= 0),
    category_id UUID REFERENCES categories(id),
    inventory_count INTEGER DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE orders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID REFERENCES users(id),
    total_amount DECIMAL(10, 2) NOT NULL,
    status VARCHAR(50) DEFAULT 'pending',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
Enter fullscreen mode Exit fullscreen mode
  • プロジェクトフォルダ構造例:
src/
├── controllers/
│   ├── auth.controller.ts
│   ├── products.controller.ts
│   └── orders.controller.ts
├── middleware/
│   ├── auth.middleware.ts
│   └── validation.middleware.ts
├── routes/
│   ├── auth.routes.ts
│   ├── products.routes.ts
│   └── orders.routes.ts
├── services/
│   ├── auth.service.ts
│   ├── products.service.ts
│   └── orders.service.ts
├── models/
│   ├── User.ts
│   ├── Product.ts
│   └── Order.ts
└── index.ts
Enter fullscreen mode Exit fullscreen mode

この出力を保存し、次のエージェントに渡します。


ステップ2: データベースオプティマイザーでスキーマレビュー

新しいセッションで以下を実行:

Activate Database Optimizer mode. (データベースオプティマイザーモードをアクティブ化)

Review this PostgreSQL schema for an e-commerce API:

[ステップ1のスキーマを貼り付け]

Check for:
1. Missing indexes on foreign keys and frequently queried columns
2. Query performance on product search (name, category, price range)
3. Proper constraints for data integrity
4. Missing tables for common e-commerce features (reviews, wishlists)
5. Soft delete patterns for audit trails

Output specific ALTER TABLE statements and new table definitions.
Enter fullscreen mode Exit fullscreen mode

期待される成果物

  • インデックス追加例:
-- 外部キーにインデックス追加
CREATE INDEX idx_products_category_id ON products(category_id);
CREATE INDEX idx_orders_user_id ON orders(user_id);

-- 製品検索用インデックス
CREATE INDEX idx_products_name_search ON products USING gin(to_tsvector('english', name));
CREATE INDEX idx_products_price ON products(price) WHERE inventory_count > 0;

-- カテゴリ+価格複合インデックス
CREATE INDEX idx_products_category_price ON products(category_id, price);
Enter fullscreen mode Exit fullscreen mode
  • 不足テーブル追加例:
CREATE TABLE reviews (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    product_id UUID REFERENCES products(id),
    user_id UUID REFERENCES users(id),
    rating INTEGER CHECK (rating >= 1 AND rating <= 5),
    comment TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(product_id, user_id)
);

CREATE TABLE cart_items (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID REFERENCES users(id),
    product_id UUID REFERENCES products(id),
    quantity INTEGER DEFAULT 1 CHECK (quantity > 0),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(user_id, product_id)
);
Enter fullscreen mode Exit fullscreen mode
  • 追加制約・ソフトデリート例:
ALTER TABLE users ADD CONSTRAINT chk_email_format
    CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');

ALTER TABLE products ADD COLUMN deleted_at TIMESTAMP WITH TIME ZONE NULL;
CREATE INDEX idx_products_deleted_at ON products(deleted_at) WHERE deleted_at IS NULL;
Enter fullscreen mode Exit fullscreen mode

推奨内容をスキーマに反映してください。


ステップ3: フロントエンドデベロッパーでクライアント構築

新しいセッションで次のプロンプトを使う:

Activate Frontend Developer mode. (フロントエンドデベロッパーモードをアクティブ化)

Build a React dashboard for this e-commerce API:

[ステップ1のOpenAPI仕様を貼り付け]

Requirements:
- TypeScript with strict mode
- React Query for server state management
- Product list with filters (category, price range, search)
- Shopping cart with real-time updates
- Order history with status tracking
- Proper error handling and loading states
- Responsive design (mobile, tablet, desktop)

Output:
1. Project setup (Vite + React + TypeScript)
2. API client with React Query hooks
3. Core components (ProductList, ProductCard, Cart, OrderHistory)
4. Error boundary and loading skeletons
Enter fullscreen mode Exit fullscreen mode

期待される成果物

  • APIクライアント例:
// src/lib/api-client.ts
import { QueryClient, useQuery, useMutation } from '@tanstack/react-query';

const API_BASE = 'http://localhost:3000/api';

async function fetcher<T>(endpoint: string, options?: RequestInit): Promise<T> {
  const response = await fetch(`${API_BASE}${endpoint}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options?.headers,
    },
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Request failed');
  }

  return response.json();
}

export function useProducts(filters?: ProductFilters) {
  const params = new URLSearchParams(filters as Record<string, string>);
  return useQuery({
    queryKey: ['products', filters],
    queryFn: () => fetcher<Product[]>(`/products?${params}`),
  });
}

export function useAddToCart() {
  return useMutation({
    mutationFn: (item: CartItem) =>
      fetcher<CartItem>('/cart', {
        method: 'POST',
        body: JSON.stringify(item),
      }),
  });
}
Enter fullscreen mode Exit fullscreen mode
  • 製品リストコンポーネント例:
// src/components/ProductList.tsx
import { useProducts } from '@/lib/api-client';
import { ProductCard } from './ProductCard';
import { FilterSidebar } from './FilterSidebar';
import { Skeleton } from './ui/skeleton';

export function ProductList() {
  const [filters, setFilters] = useState<ProductFilters>({});
  const { data: products, isLoading, error } = useProducts(filters);

  if (error) {
    return <Alert variant="destructive">{error.message}</Alert>;
  }

  return (
    <div className="flex gap-4">
      <FilterSidebar filters={filters} onFilterChange={setFilters} />
      <div className="flex-1 grid grid-cols-1 md:grid-cols-3 gap-4">
        {isLoading ? (
          Array.from({ length: 6 }).map((_, i) => (
            <Skeleton key={i} className="h-64" />
          ))
        ) : products?.length === 0 ? (
          <EmptyState message="No products found" />
        ) : (
          products?.map(product => (
            <ProductCard key={product.id} product={product} />
          ))
        )}
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • エラーバウンダリ例:
// src/components/ErrorBoundary.tsx
export class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean; error: Error | null }
> {
  constructor(props: { children: React.ReactNode }) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="p-4 bg-red-50 border border-red-200 rounded">
          <h2 className="text-lg font-semibold text-red-800">何か問題が発生しました</h2>
          <p className="text-red-600">{this.state.error?.message}</p>
          <Button onClick={() => window.location.reload()} className="mt-2">
            再読み込み
          </Button>
        </div>
      );
    }

    return this.props.children;
  }
}
Enter fullscreen mode Exit fullscreen mode

ステップ4: コードレビュアーでセキュリティ&型安全診断

新しいセッションで以下を入力:

Activate Code Reviewer mode. (コードレビュアーモードをアクティブ化)

Review this codebase for:

1. Security vulnerabilities:
   - SQL injection risks
   - XSS vulnerabilities
   - CSRF protection
   - Authentication bypass possibilities

2. TypeScript strict mode compliance:
   - No implicit any
   - Proper type definitions
   - Null/undefined handling

3. Error handling gaps:
   - Uncaught promise rejections
   - Missing try/catch blocks
   - Silent failures

[ステップ1~3のコードを貼り付け]

Output a report with severity ratings (Critical, High, Medium, Low) and specific fixes.
Enter fullscreen mode Exit fullscreen mode

期待される成果物

  • セキュリティレポート例:
## 致命的な問題 (Critical Issues)

### 1. 製品検索におけるSQLインジェクション
**場所:** `src/controllers/products.controller.ts:24`
**問題:** ユーザー入力がSQLクエリに直接連結されている
Enter fullscreen mode Exit fullscreen mode


typescript
// VULNERABLE
const query = SELECT * FROM products WHERE name LIKE '%${search}%';

**修正:** パラメータ化クエリを使用する

Enter fullscreen mode Exit fullscreen mode


typescript
const query = 'SELECT * FROM products WHERE name LIKE $1';
await db.query(query, [%${search}%]);

Enter fullscreen mode Exit fullscreen mode


typescript

  • CSRF対策例:
重大な問題 (High Issues)

2. CSRF保護の不足
**場所:** src/index.ts
**問題:** 状態変更操作に対するCSRFミドルウェアがない
**修正:** csurfミドルウェアを追加する

Enter fullscreen mode Exit fullscreen mode


typescript
import csrf from 'csurf';
app.use(csrf({ cookie: true }));

Enter fullscreen mode Exit fullscreen mode


typescript

  • 型安全性・エラー処理の指摘例:
中程度の問題 (Medium Issues)

3. API応答における暗黙のany
**場所:** src/lib/api-client.ts:8
**問題:** fetcher関数の汎用的なany型
**修正:** 適切な型制約を追加する

Enter fullscreen mode Exit fullscreen mode


typescript
async function fetcher>(
endpoint: string,
options?: RequestInit
): Promise { ... }


**型安全性レポート:**
1. products.controller.ts:45 - 戻り値の型アノテーションが不足
2. auth.middleware.ts:12 - catchブロック内の暗黙のany
3. orders.service.ts:78 - オブジェクトが未定義である可能性あり

`tsc --noEmit`を実行し、型エラーをデプロイ前に全て修正してください。
Enter fullscreen mode Exit fullscreen mode


plaintext

指摘された問題をすべて修正し、次に進みます。


ステップ5: リアリティチェッカーで出荷前検証

新しいセッションで以下を実行:

Activate Reality Checker mode. (リアリティチェッカーモードをアクティブ化)

This e-commerce API is ready for production validation.

Run your mandatory reality check process:

1. Verify files exist
2. Cross-reference claimed features with actual code
3. Require screenshot evidence from Playwright tests
4. Review test-results.json for performance metrics

Project URL: http://localhost:3000
Test results: ./public/qa-screenshots/test-results.json

Output: PASS or NEEDS WORK with specific blocking issues.
Enter fullscreen mode Exit fullscreen mode

チェック例

  • ファイル・機能・証拠コマンド:
# ファイルの存在確認
ls -la src/controllers/ src/services/ src/routes/
ls -la src/components/ src/lib/

# 機能実装のgrep検索
grep -r "jwt\|jsonwebtoken" . --include="*.ts" || echo "NO JWT FOUND"
grep -r "bcrypt\|argon2" . --include="*.ts" || echo "NO PASSWORD HASHING FOUND"
grep -r "rateLimit\|express-rate-limit" . --include="*.ts" || echo "NO RATE LIMITING FOUND"

# Playwrightスクリーンショット実行
npx playwright test --config=qa-playwright.config.ts --grep "@screenshot"

# テスト結果確認
cat public/qa-screenshots/test-results.json
Enter fullscreen mode Exit fullscreen mode
  • 検証レポート例:
## リアリティチェック結果 (Reality Check Results)

### ファイル検証: PASS (合格)
- すべてのコントローラーファイルが存在
- すべてのコンポーネントファイルが存在

### 機能検証: NEEDS WORK (作業が必要)
- JWT認証: FOUND
- パスワードハッシュ: FOUND
- レート制限: NOT FOUND (ブロッキング)

### スクリーンショット証拠: NEEDS WORK (作業が必要)
- デスクトップレイアウト: PASS
- タブレットレイアウト: PASS
- モバイルレイアウト: FAIL (製品グリッドが375pxで破損)

### パフォーマンスメトリクス: NEEDS WORK (作業が必要)
- 平均ロード時間: 2.3秒 (目標: <1秒)
- コンソールエラー: 3個 (目標: 0個)
- 失敗したネットワークリクエスト: 1個 (目標: 0個)

## 最終ステータス: NEEDS WORK (作業が必要)

### ブロッキング問題:
1. レート制限が実装されていない
2. 製品リストのモバイルレイアウトが破損している
3. 3つのコンソールエラーを修正する必要がある
4. ロード時間が目標の1秒を超えている

### 非ブロッキング問題:
- 注文履歴にローディングスケルトンを追加
- エラーメッセージを改善
Enter fullscreen mode Exit fullscreen mode

指摘されたブロッキング問題を修正し、再度Reality Checkerを実行してください。


ワークフロー概要

┌─────────────────────────────────────────────────────────────────┐
│  Backend Architect (バックエンドアーキテクト)                       │
│  → OpenAPI仕様、データベーススキーマ、フォルダ構造              │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  Database Optimizer (データベースオプティマイザー)              │
│  → インデックス推奨、不足しているテーブル、制約               │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  Frontend Developer (フロントエンドデベロッパー)                │
│  → Reactコンポーネント、APIクライアント、エラー処理             │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  Code Reviewer (コードレビュアー)                                 │
│  → セキュリティ監査、型安全性、エラー処理のギャップ             │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  Reality Checker (リアリティチェッカー)                           │
│  → 証拠に基づく検証、スクリーンショット証明、PASS/FAIL          │
└─────────────────────────────────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

並列エージェント実行 (上級)

複数ターミナルでエージェントを並列実行し、ワークフロー時間を短縮できます。

# Terminal 1: Backend Architect
claude "Activate Backend Architect. Design e-commerce API..."

# Terminal 2: Database Optimizer (wait for schema output)
claude "Activate Database Optimizer. Review this schema..."

# Terminal 3: Frontend Developer (wait for API spec)
claude "Activate Frontend Developer. Build React dashboard..."

# Terminal 4: Code Reviewer (wait for code)
claude "Activate Code Reviewer. Review this codebase..."

# All terminals: Reality Checker (final validation)
claude "Activate Reality Checker. Run mandatory checks..."
Enter fullscreen mode Exit fullscreen mode

この方法なら全工程を6~8時間ではなく2~4時間で完了できます。


構築したもの

成果物 エージェント 出力
API設計 Backend Architect (バックエンドアーキテクト) OpenAPI仕様、データベーススキーマ、フォルダ構造
スキーマ最適化 Database Optimizer (データベースオプティマイザー) インデックス推奨、追加テーブル、制約
フロントエンド Frontend Developer (フロントエンドデベロッパー) Reactコンポーネント、APIクライアント、エラーバウンダリ
セキュリティ監査 Code Reviewer (コードレビュアー) 脆弱性レポート、型安全性修正
最終検証 Reality Checker (リアリティチェッカー) スクリーンショット証拠、PASS/FAIL認証

次のステップ

APIをデプロイする:

  • 接続プールを備えた本番PostgreSQLをセットアップする
  • シークレット用の環境変数を設定する
  • ヘルスチェックエンドポイントを追加する
  • 監視 (Prometheus、Grafana) をセットアップする

ワークフローを拡張する:

  • 負荷テスト用にPerformance Benchmarkerエージェントを追加する
  • ドキュメント作成用にTechnical Writerエージェントを追加する
  • CI/CDパイプライン用にDevOps Automatorエージェントを追加する

パターンを再利用する:

  • プロンプトをテンプレートとして保存する
  • エージェントセッションを連結するワークフロースクリプトを作成する
  • チームと共有する

5つの専門エージェント。1つの完全なAPI。汎用的なアドバイスは不要。

これが専門化の力です。各エージェントは自身の専門領域を知り、チェックリストと成果物を出します。

あなたの番です。プロジェクトを選び、エージェントをアクティブ化し、より迅速に出荷しましょう。


主なポイント

  • 専門エージェントは汎用アシスタントよりも優れています — 各エージェントは専門知識、チェックリスト、具体的な成果物を持っています
  • シーケンシャルなワークフローが品質を保証します — バックエンドアーキテクトが設計し、データベースオプティマイザーがレビューし、フロントエンドデベロッパーが構築し、コードレビュアーが監査し、リアリティチェッカーが検証します
  • 証拠に基づいた承認がバグを防ぎます — リアリティチェッカーは、PASS認証の前にスクリーンショットの証拠、grep結果、パフォーマンスメトリクスを要求します
  • 並列実行が合計時間を短縮します — 4つのターミナルを同時に実行することで、6〜8時間ではなく2〜4時間で完了できます
  • プロンプトをテンプレートとして保存します — 同じエージェントアクティベーションを再利用して、プロジェクト全体で一貫した結果を得ることができます

よくある質問

開発者向けAIエージェントとは何ですか?

AIエージェントは、ドメイン知識を持つ専門のAIアシスタントです。汎用チャットボットとは異なり、バックエンドアーキテクトやコードレビュアーのようなエージェントは、特定のチェックリストを持ち、一貫した成果物を生成します。

The Agencyのエージェントをインストールするには?

github.com/msitarzewski/agency-agentsからリポジトリをクローンし、.mdファイルをClaude Codeの~/.claude/agents/にコピー。または他のツール用インストールスクリプトを利用。

Reality Checkerエージェントとは?

Reality Checkerは、証拠なしには作業を承認しない、証拠に基づくQAエージェントです。PASS認証を与える前に、スクリーンショット、grep結果、パフォーマンスメトリクスを要求します。

複数のエージェントを並列で実行できますか?

はい。複数のターミナルで異なるエージェントをアクティブ化し、出力をコピーまたはMCPメモリで自動ハンドオフします。

エージェント間でコンテキストを渡すには?

あるエージェントの出力を次のエージェントの入力に貼り付けます。自動の場合はMCPメモリで成果物を管理。

エージェントがNEEDS WORKと言ったら?

ブロッキング問題を修正し、エージェントを再実行します。Reality Checkerは修正要件をリストアップします。

すべてのプロジェクトに5つのエージェントすべてが必要ですか?

いいえ。APIプロジェクトならバックエンドアーキテクトとコードレビュアーから開始。複雑なスキーマにはデータベースオプティマイザー、UI作業にはフロントエンドデベロッパー、出荷前にはリアリティチェッカーを追加してください。

Top comments (0)