AgileFlow

API

PreviousNext

Services and data layer specialist for implementing backend APIs, business logic, and data models.

API Agent

The API agent (AG-API) is your backend services specialist. It implements REST/GraphQL APIs, business logic, data models, database access, external service integrations, and state management. It ensures your data layer is secure, performant, and well-tested.

Capabilities

  • Implement REST/GraphQL/tRPC API endpoints
  • Write business logic and validation rules
  • Design and maintain data models and schemas
  • Optimize database queries and prevent N+1 problems
  • Integrate external services (Stripe, SendGrid, analytics, etc.)
  • Implement authentication and authorization
  • Write comprehensive API tests (unit, integration, contract)
  • Document API endpoints and error handling
  • Coordinate with AG-UI on API endpoint dependencies
  • Monitor and log API requests with context

When to Use

Use the API agent when:

  • You need to implement a new API endpoint
  • You need to add business logic to handle a feature
  • You need to integrate an external service (payment, email, etc.)
  • You need to optimize database queries or fix N+1 problems
  • You need to implement authentication or authorization
  • You're designing data models for a new feature
  • You need to write comprehensive API tests
  • You want to ensure AG-UI stories aren't blocked waiting for endpoints

How It Works

  1. Context Loading: Agent reads expertise, CLAUDE.md, and architecture docs
  2. Status Check: Agent finds ready stories and checks for AG-UI blockers
  3. Definition of Ready: Agent validates acceptance criteria and test stubs
  4. Plan Mode: For complex work, agent designs approach before implementing
  5. Implementation: Agent writes validation, error handling, and business logic
  6. Testing: Agent writes unit, integration, and contract tests
  7. Coordination: Agent unblocks AG-UI stories when endpoints are ready
  8. Verification: Agent runs tests to ensure baseline passes
  9. Documentation: Agent updates CLAUDE.md and appends bus messages

Example

# Via /babysit (recommended)
/agileflow:babysit
> "I need a user profile API endpoint"

The API agent will:

  1. Check docs/06-stories/ for US with owner==AG-API
  2. Look for any AG-UI stories blocked waiting on this endpoint
  3. Implement POST /api/users endpoint:
    • Input validation (required fields, type checking)
    • Business logic (hash password, set defaults)
    • Database access (insert into users table)
    • Error handling (duplicate email, validation errors)
    • Logging with request IDs
  4. Write comprehensive tests:
    • Happy path (valid data creates user)
    • Validation errors (missing email)
    • Edge cases (very long email)
  5. Update API docs (OpenAPI/Swagger)
  6. Send unblock message to AG-UI: "GET /api/users/:id ready"
  7. Mark in-review when tests pass

Or spawn directly:

Task(
  description: "Implement payment webhook endpoint",
  prompt: "Add Stripe webhook handler for payment.success and payment.failed events",
  subagent_type: "agileflow-api"
)

Key Behaviors

  • Load Expertise First: Reads expertise.yaml before any work
  • Prioritize AG-UI Unblocking: Checks for AG-UI stories blocked on API endpoints - those are top priority
  • Proactive Coordination: Sends unblock messages to AG-UI when endpoints are ready
  • Input Validation: Always validates types, formats, ranges, and authorization
  • Error Handling: Consistent error schema with HTTP status codes
  • Test-Driven: Writes tests before implementation, ensures tests pass before in-review
  • CLAUDE.md Updates: Documents new API patterns discovered during implementation
  • Session Harness Integration: Verifies test status before starting, requires passing tests before in-review
  • Autonomous Commands: Directly invokes /agileflow:ai-code-review, /agileflow:adr-new, etc.
  • Bus Coordination: Sends status, blocked, unblock, and question messages to bus/log.jsonl
  • Context Preservation: Uses compact_context (priority: critical) to maintain focus during long conversations, preserving expertise loading rules and blocker tracking through context compaction

Compact Context Configuration

The API agent uses critical priority compact_context to ensure focus is maintained during extended conversations:

compact_context:
  priority: critical
  preserve_rules:
    - "LOAD EXPERTISE FIRST: Always read packages/cli/src/core/experts/api/expertise.yaml"
    - "CHECK FOR AG-UI BLOCKERS: Search bus/log.jsonl for UI stories waiting on API endpoints"
    - "VERIFY TEST BASELINE: Session harness required - check test_status before starting"
    - "DIFF-FIRST FOR FILE CHANGES: Show all edits with YES/NO confirmation"
    - "NEVER hardcode secrets - use environment variables only"
  state_fields:
    - current_story
    - endpoints_implemented
    - blocked_ui_stories
    - test_status_baseline

This ensures critical rules (expertise loading, blocker prioritization, test verification) and current state (which endpoints are done, what UI stories are blocked) are preserved even after context compaction.

Tools Available

This agent has access to: Read, Write, Edit, Bash, Glob, Grep

API Endpoint Patterns

REST Conventions:

GET    /api/users           → List users
POST   /api/users           → Create user
GET    /api/users/:id       → Get user
PATCH  /api/users/:id       → Update user
DELETE /api/users/:id       → Delete user

Request/Response Format:

// Request
POST /api/users
{
  "email": "user@example.com",
  "password": "secure-password",
  "name": "John Doe"
}
 
// Success Response (201 Created)
{
  "id": "user_123",
  "email": "user@example.com",
  "name": "John Doe",
  "createdAt": "2025-01-15T10:00:00Z"
}
 
// Error Response (422 Unprocessable Entity)
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Validation failed",
    "details": {
      "email": "Email already exists"
    }
  }
}

Input Validation

Every endpoint must validate inputs:

// Validate required fields
if (!email || !password) {
  throw new ValidationError('Email and password required');
}
 
// Validate format
if (!email.includes('@')) {
  throw new ValidationError('Invalid email format');
}
 
// Validate range
if (password.length \< 8) {
  throw new ValidationError('Password must be 8+ characters');
}
 
// Validate authorization
if (userId !== req.user.id) {
  throw new AuthorizationError('Cannot access other users');
}

Error Handling

Consistent error schema across all endpoints:

// Error class (example)
class AppError extends Error {
  constructor(code, message, statusCode = 500, details = {}) {
    super(message);
    this.code = code;
    this.statusCode = statusCode;
    this.details = details;
  }
}
 
// Usage
throw new AppError(
  'VALIDATION_ERROR',
  'Email is required',
  422,
  { field: 'email' }
);

Testing Standards

Every API endpoint needs comprehensive tests:

describe('POST /api/users', () => {
  test('creates user with valid data', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ email: 'test@example.com', password: 'password123' });
    expect(response.status).toBe(201);
    expect(response.body.email).toBe('test@example.com');
  });
 
  test('returns validation error for missing email', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ password: 'password123' });
    expect(response.status).toBe(422);
    expect(response.body.error.code).toBe('VALIDATION_ERROR');
  });
 
  test('returns error for duplicate email', async () => {
    // Create first user
    await request(app)
      .post('/api/users')
      .send({ email: 'test@example.com', password: 'password123' });
 
    // Try to create duplicate
    const response = await request(app)
      .post('/api/users')
      .send({ email: 'test@example.com', password: 'password123' });
    expect(response.status).toBe(409);
    expect(response.body.error.code).toBe('DUPLICATE_EMAIL');
  });
});

Key Files

  • Expertise: packages/cli/src/core/experts/api/expertise.yaml (agent memory)
  • Workflow: packages/cli/src/core/experts/api/workflow.md (Plan → Build → Self-Improve)
  • Status: docs/09-agents/status.json (story tracking)
  • Bus: docs/09-agents/bus/log.jsonl (coordination messages)
  • CLAUDE.md: API architecture, ORM, validation approach
  • Research: docs/10-research/ (check for API patterns)
  • ADRs: docs/03-decisions/ (API architecture decisions)

Workflow Steps

  1. Load Expertise: Read expertise.yaml
  2. Check Status: Find READY stories where owner==AG-API
  3. Prioritize AG-UI Blockers: Check bus for AG-UI stories blocked on endpoints
  4. Validate Definition of Ready: AC exists, test stub in docs/07-testing/test-cases/
  5. Check Session Harness: Verify test_status==passing before starting
  6. Create Branch: feature/<US_ID>-<slug>
  7. Update Status: Mark "in-progress", append bus message
  8. Implement: Validation, error handling, business logic, tests
  9. Run Verification: /agileflow:verify to ensure tests pass
  10. Update CLAUDE.md: If new patterns established (document them)
  11. Mark In-Review: Only if test_status==passing
  12. Send Unblock Messages: If AG-UI was waiting on this endpoint
  13. Generate PR: Use /agileflow:pr-template
  14. Self-Improve: Run self-improve.md after completion

Quality Checklist

Before marking in-review:

  • Inputs validated (type, format, range, auth)
  • Error responses consistent (HTTP codes, error schema)
  • Auth/authorization enforced on protected routes
  • No N+1 queries (optimized database access)
  • Secrets in env vars (never hardcoded)
  • Logging with request IDs and context
  • API docs updated (OpenAPI/Swagger/README)
  • Tests cover: happy path, validation errors, auth failures, edge cases
  • Test status: passing (verified via /agileflow:verify)
  • AG-UI stories unblocked (sent unblock message if applicable)

Coordination with Other Agents

AG-UI (Frontend):

  • Check docs/09-agents/bus/log.jsonl for UI stories blocked waiting on endpoints
  • When endpoint ready, send unblock message with method, path, request/response format
  • Example: "API endpoint GET /api/users/:id ready (200 OK, user object), unblocking US-0042"

AG-DATABASE (Data Layer):

  • Coordinate on schema design before implementing queries
  • Review migrations before using in code
  • Share query patterns for optimization

AG-CI (Testing):

  • Coordinate on test database setup
  • Request contract testing infrastructure (Pact, MSW)
  • Ensure API tests in CI

MENTOR (Orchestration):

  • Request clarification on unclear business logic
  • Report if story missing Definition of Ready
  • ui - Frontend components that consume API endpoints
  • database - Data layer and schema design
  • mentor - Orchestrates API work as part of feature implementation