{
  "name": "API Development Workflow",
  "description": "Standardized workflow for REST/GraphQL API endpoint development",
  "workflowType": "api-development",
  "applicablePatterns": ["REST", "GraphQL", "WebSocket"],
  "phases": {
    "planning": {
      "description": "API design and specification phase",
      "activities": [
        "Define API contract and OpenAPI specification",
        "Design request/response schemas",
        "Plan error handling and status codes",
        "Consider rate limiting and pagination",
        "Document authentication and authorization requirements"
      ]
    },
    "implementation": {
      "description": "Core API implementation phase",
      "activities": [
        "Create controller/resolver with proper routing",
        "Implement service layer with business logic",
        "Add input validation and sanitization",
        "Implement proper error handling",
        "Add authentication and authorization guards"
      ]
    },
    "testing": {
      "description": "Comprehensive API testing phase",
      "activities": [
        "Write unit tests for service layer",
        "Create integration tests for endpoints",
        "Test error scenarios and edge cases",
        "Validate API documentation accuracy",
        "Perform security testing"
      ]
    },
    "documentation": {
      "description": "API documentation and examples",
      "activities": [
        "Generate/update OpenAPI documentation",
        "Create usage examples and tutorials",
        "Document rate limits and quotas",
        "Add error code documentation",
        "Update API versioning information"
      ]
    }
  },
  "implementationPatterns": {
    "controller": {
      "structure": "Thin controller with business logic in services",
      "validation": "Use DTOs for input validation",
      "responses": "Standardized response format",
      "errors": "Consistent error handling middleware",
      "documentation": "Comprehensive API documentation decorators"
    },
    "service": {
      "business_logic": "Core business logic implementation",
      "data_access": "Repository pattern for data operations",
      "transactions": "Database transaction management",
      "caching": "Implement caching where appropriate",
      "external_apis": "Handle external API integrations"
    },
    "validation": {
      "input": "Validate all input parameters and body data",
      "sanitization": "Sanitize inputs to prevent injection attacks",
      "authorization": "Verify user permissions for operations",
      "rate_limiting": "Implement appropriate rate limiting",
      "idempotency": "Support idempotent operations where needed"
    },
    "responses": {
      "success": "Consistent success response format",
      "errors": "Standardized error response structure",
      "pagination": "Implement cursor or offset pagination",
      "filtering": "Support query filtering and sorting",
      "versioning": "Handle API versioning appropriately"
    }
  },
  "qualityGates": {
    "pre_implementation": [
      "API specification reviewed and approved",
      "Data models and schemas defined",
      "Authentication requirements clarified",
      "Rate limiting strategy determined",
      "Error handling approach documented"
    ],
    "implementation": [
      "Code follows established patterns and conventions",
      "Input validation implemented for all parameters",
      "Proper error handling and logging added",
      "Authentication and authorization enforced",
      "Business logic separated from controller logic"
    ],
    "testing": [
      "Unit tests cover all service methods",
      "Integration tests validate API contracts",
      "Error scenarios properly tested",
      "Performance tests pass acceptance criteria",
      "Security tests identify no critical vulnerabilities"
    ],
    "deployment": [
      "API documentation is accurate and complete",
      "Monitoring and alerting configured",
      "Database migrations applied successfully",
      "Configuration validated in target environment",
      "Rollback procedures documented and tested"
    ]
  },
  "testingStrategy": {
    "unit_tests": {
      "scope": "Individual service methods and business logic",
      "mocking": "Mock external dependencies and database",
      "coverage": "Minimum 80% code coverage",
      "focus": "Business logic and edge cases"
    },
    "integration_tests": {
      "scope": "Full API endpoint testing with real database",
      "scenarios": "Happy path and error scenarios",
      "data": "Use test fixtures and factories",
      "cleanup": "Clean up test data after each test"
    },
    "contract_tests": {
      "scope": "API contract validation",
      "tools": "OpenAPI validation and contract testing",
      "versioning": "Backward compatibility testing",
      "documentation": "Ensure examples work correctly"
    },
    "performance_tests": {
      "scope": "Load and stress testing",
      "metrics": "Response time, throughput, resource usage",
      "scenarios": "Normal and peak load conditions",
      "bottlenecks": "Identify and address performance issues"
    },
    "security_tests": {
      "scope": "Authentication, authorization, and input validation",
      "scenarios": "SQL injection, XSS, authentication bypass",
      "tools": "Automated security scanning",
      "compliance": "Ensure regulatory compliance requirements"
    }
  },
  "codeTemplates": {
    "restController": {
      "framework": "universal",
      "template": "// REST Controller Template\n@Controller('/api/v1/users')\n@ApiTags('users')\nexport class UsersController {\n  constructor(private usersService: UsersService) {}\n\n  @Get()\n  @ApiOperation({ summary: 'Get all users' })\n  @ApiResponse({ status: 200, description: 'Users retrieved successfully' })\n  async getUsers(@Query() query: GetUsersDto): Promise<ApiResponse<User[]>> {\n    const users = await this.usersService.getUsers(query);\n    return { data: users, message: 'Users retrieved successfully' };\n  }\n\n  @Post()\n  @ApiOperation({ summary: 'Create new user' })\n  @ApiResponse({ status: 201, description: 'User created successfully' })\n  async createUser(@Body() createUserDto: CreateUserDto): Promise<ApiResponse<User>> {\n    const user = await this.usersService.createUser(createUserDto);\n    return { data: user, message: 'User created successfully' };\n  }\n}"
    },
    "serviceLayer": {
      "framework": "universal",
      "template": "// Service Layer Template\n@Injectable()\nexport class UsersService {\n  constructor(private usersRepository: UsersRepository) {}\n\n  async getUsers(query: GetUsersDto): Promise<User[]> {\n    try {\n      const users = await this.usersRepository.findWithFilters(query);\n      return users;\n    } catch (error) {\n      throw new ServiceException('Failed to retrieve users', error);\n    }\n  }\n\n  async createUser(createUserDto: CreateUserDto): Promise<User> {\n    try {\n      const existingUser = await this.usersRepository.findByEmail(createUserDto.email);\n      if (existingUser) {\n        throw new ConflictException('User with this email already exists');\n      }\n      \n      const user = await this.usersRepository.create(createUserDto);\n      return user;\n    } catch (error) {\n      throw new ServiceException('Failed to create user', error);\n    }\n  }\n}"
    },
    "integrationTest": {
      "framework": "universal",
      "template": "// Integration Test Template\ndescribe('Users API', () => {\n  let app: TestingModule;\n  let httpServer: any;\n\n  beforeAll(async () => {\n    app = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile();\n    \n    httpServer = app.createNestApplication();\n    await httpServer.init();\n  });\n\n  describe('GET /api/v1/users', () => {\n    it('should return users list', async () => {\n      const response = await request(httpServer)\n        .get('/api/v1/users')\n        .expect(200);\n\n      expect(response.body.data).toBeInstanceOf(Array);\n      expect(response.body.message).toBe('Users retrieved successfully');\n    });\n\n    it('should handle pagination', async () => {\n      const response = await request(httpServer)\n        .get('/api/v1/users?page=1&limit=10')\n        .expect(200);\n\n      expect(response.body.data.length).toBeLessThanOrEqual(10);\n    });\n  });\n\n  describe('POST /api/v1/users', () => {\n    it('should create new user', async () => {\n      const newUser = {\n        name: 'John Doe',\n        email: 'john@example.com'\n      };\n\n      const response = await request(httpServer)\n        .post('/api/v1/users')\n        .send(newUser)\n        .expect(201);\n\n      expect(response.body.data.name).toBe(newUser.name);\n      expect(response.body.data.email).toBe(newUser.email);\n    });\n\n    it('should validate required fields', async () => {\n      const response = await request(httpServer)\n        .post('/api/v1/users')\n        .send({})\n        .expect(400);\n\n      expect(response.body.errors).toBeDefined();\n    });\n  });\n});"
    }
  },
  "bestPractices": [
    "Use consistent REST conventions for endpoint naming",
    "Implement proper HTTP status codes for different scenarios",
    "Add comprehensive input validation and sanitization",
    "Use DTOs for request/response data structures",
    "Implement proper error handling with meaningful messages",
    "Add rate limiting to prevent API abuse",
    "Use pagination for endpoints returning large datasets",
    "Implement API versioning strategy from the start",
    "Add comprehensive logging for debugging and monitoring",
    "Use dependency injection for better testability",
    "Implement proper authentication and authorization",
    "Add API documentation with examples and use cases"
  ],
  "commonPitfalls": [
    "Putting business logic directly in controllers",
    "Not validating input parameters properly",
    "Inconsistent error handling and response formats",
    "Missing or outdated API documentation",
    "Not implementing proper pagination",
    "Ignoring rate limiting and abuse prevention",
    "Poor error messages that don't help clients",
    "Not versioning APIs properly",
    "Missing or inadequate logging",
    "Not testing error scenarios thoroughly",
    "Exposing sensitive information in error responses",
    "Not handling database connection failures gracefully"
  ]
}
