Skip to content

SabariVivek/API-Playwright-TypeScript-Framework

Repository files navigation

API Automation Testing Framework

A comprehensive, production-ready end-to-end API automation testing framework built with Playwright and TypeScript. This framework follows industry best practices and implements all key considerations for scalable, maintainable, and reliable API testing.

🎯 Key Features

Core Architecture

  • βœ… API Client Layer - Abstraction layer for HTTP requests with retry logic
  • βœ… Environment Configuration - Multi-environment support (dev, staging, prod)
  • βœ… Authentication Management - Global token handling and credential management
  • βœ… Request Builder - Fluent API for building complex requests
  • βœ… Response Validation - Centralized validation logic with schema support
  • βœ… Test Data Management - Dynamic + static data with Faker and Factory pattern
  • βœ… Fixtures - Dependency injection for test isolation

Advanced Features

  • βœ… Comprehensive Assertions - Status code, body, schema, headers, response time
  • βœ… Centralized Logging - Request/response logging with Pino
  • βœ… HTML Reporting - Professional test reports and metrics
  • βœ… Error Handling - Centralized error management
  • βœ… Parallel Execution - Native Playwright parallel support
  • βœ… Retry Mechanism - Handle flaky APIs gracefully
  • βœ… Schema Validation - AJV and Zod support
  • βœ… Test Isolation - Fresh data and setup/teardown

CI/CD Integration

  • βœ… GitHub Actions - Complete workflow with multiple environments
  • βœ… Azure DevOps - Pipeline with matrix strategy
  • βœ… Jenkins - Declarative pipeline with email notifications
  • βœ… Security - Environment variables for sensitive data
  • βœ… Notifications - Slack integration for test results

πŸ“‹ Project Structure

api-automation-framework/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/                 # Configuration management
β”‚   β”‚   β”œβ”€β”€ env.ts             # Environment variables
β”‚   β”‚   └── config.ts          # Logger and config export
β”‚   β”‚
β”‚   β”œβ”€β”€ clients/               # API client layer
β”‚   β”‚   β”œβ”€β”€ baseClient.ts      # Base HTTP client (retry logic)
β”‚   β”‚   β”œβ”€β”€ userClient.ts      # User API client
β”‚   β”‚   └── authClient.ts      # Authentication client
β”‚   β”‚
β”‚   β”œβ”€β”€ utils/                 # Utility functions
β”‚   β”‚   β”œβ”€β”€ requestBuilder.ts  # Fluent request builder
β”‚   β”‚   β”œβ”€β”€ responseValidator.ts # Response validation
β”‚   β”‚   β”œβ”€β”€ dataGenerator.ts   # Test data generation
β”‚   β”‚   └── helpers.ts         # Helper utilities
β”‚   β”‚
β”‚   β”œβ”€β”€ models/                # Data models
β”‚   β”‚   └── userModel.ts       # User data model
β”‚   β”‚
β”‚   β”œβ”€β”€ test-data/             # Static test data
β”‚   β”‚   └── userData.json      # Sample user data
β”‚   β”‚
β”‚   β”œβ”€β”€ tests/                 # Test suites
β”‚   β”‚   β”œβ”€β”€ user.spec.ts       # User API tests
β”‚   β”‚   └── auth.spec.ts       # Authentication tests
β”‚   β”‚
β”‚   └── fixtures/              # Test fixtures
β”‚       └── apiFixture.ts      # API fixture setup
β”‚
β”œβ”€β”€ .github/workflows/         # GitHub Actions
β”‚   └── api-tests.yml
β”‚
β”œβ”€β”€ scripts/                   # Utility scripts
β”‚   β”œβ”€β”€ run-tests.sh
β”‚   └── pre-commit.sh
β”‚
β”œβ”€β”€ playwright.config.ts       # Playwright configuration
β”œβ”€β”€ tsconfig.json             # TypeScript configuration
β”œβ”€β”€ package.json              # Dependencies
β”œβ”€β”€ .env.example              # Environment template
└── README.md                 # Documentation

πŸš€ Getting Started

Prerequisites

  • Node.js 18+
  • npm or yarn
  • Git

Installation

# Clone the repository
git clone <repository-url>
cd api-automation-framework

# Install dependencies
npm install

# Install Playwright browsers
npx playwright install

Configuration

# Copy environment template
cp .env.example .env

# Edit .env with your configuration
nano .env

Environment Variables:

NODE_ENV=development
BASE_URL=https://jsonplaceholder.typicode.com
API_TIMEOUT=30000
AUTH_TOKEN=your_token_here
API_KEY=your_api_key_here
ENVIRONMENT=development
LOG_LEVEL=info
RETRY_ATTEMPTS=3
RETRY_DELAY=1000

πŸ“ Running Tests

All Tests

npm test

Tests with UI

npm run test:ui

Debug Mode

npm run test:debug

Headed Mode (See Browser)

npm run test:headed

Parallel Execution

npm run test:parallel

Sequential Execution

npm run test:sequential

Specific Test File

npx playwright test src/tests/user.spec.ts

Specific Test Suite

npx playwright test -g "User API Tests"

πŸ“Š Viewing Reports

# Generate HTML report
npm run test:reporter

# View HTML report
npm run report

πŸ—οΈ Architecture & Design Patterns

1. API Client Pattern

// Base client with retry logic and error handling
const userClient = new UserClient();
const response = await userClient.getUserById(1);

2. Factory Pattern

// Generate test data dynamically
const user = TestDataFactory.createUser({
  name: 'Custom Name'
});

3. Builder Pattern

// Build complex requests fluently
const request = createRequestBuilder()
  .addField('name', 'John')
  .addField('email', 'john@example.com')
  .withAuthToken(token);

4. Fixture Pattern

// Dependency injection in tests
test('test name', async ({ userClient, responseValidator, dataGenerator }) => {
  // Use injected dependencies
});

πŸ§ͺ Writing Tests

Basic Test Example

import { test, expect } from '@fixtures/apiFixture';

test('should get user by ID', async ({ userClient, responseValidator }) => {
  // Setup
  const userId = 1;

  // Execute
  const response = await userClient.getUserById(userId);

  // Assert - Status
  expect(responseValidator.validateStatus(response.status, 200)).toBe(true);

  // Assert - Body
  expect(response.data.id).toBe(userId);
  expect(response.data.name).toBeTruthy();

  // Assert - Response Time
  expect(responseValidator.validateResponseTime(response.responseTime, 3000)).toBe(true);
});

Advanced Test Example with Schema Validation

test('should validate user schema', async ({ userClient, responseValidator }) => {
  const response = await userClient.getUserById(1);

  const schemaValidation = responseValidator.validateSchema(response.data, userSchema);
  expect(schemaValidation.isValid).toBe(true);
});

πŸ” Security Best Practices

βœ… DO

  • Store sensitive data in .env file
  • Use environment variables for tokens/keys
  • Rotate tokens regularly
  • Validate SSL certificates
  • Log without sensitive data
  • Use HTTPS only in production

❌ DON'T

  • Hardcode passwords or tokens
  • Commit .env file to repository
  • Log sensitive information
  • Use self-signed certificates
  • Skip certificate validation

πŸ“ˆ Performance Considerations

Response Time Validation

// Validate response time SLA
expect(responseValidator.validateResponseTime(responseTime, 3000)).toBe(true);

Parallel Execution

npm run test:parallel  # Uses 4 workers by default

Retry Configuration

// Configurable in .env
RETRY_ATTEMPTS=3
RETRY_DELAY=1000  // milliseconds

πŸ”„ CI/CD Integration

GitHub Actions

# Automatically runs on:
# - Push to main/develop
# - Pull requests
# - Daily schedule (2 AM UTC)

Triggers tests across multiple environments (dev, staging, prod) with:

  • Parallel execution
  • HTML/JUnit/JSON reports
  • Artifact upload
  • PR comments
  • Slack notifications

Azure DevOps

# Run with:
# - Matrix strategy for multiple environments
# - Artifact publishing
# - Test results reporting

Jenkins

// Run with:
// - Parameter selection (environment, sequential/parallel)
// - Email notifications
// - Test result archiving

πŸ› οΈ Code Quality

Linting

npm run lint

Type Checking

npm run type-check

Code Formatting

npm run format

ESLint Configuration

  • Strict TypeScript rules
  • No implicit any
  • No unused variables
  • Single quotes required
  • Semicolons required

Prettier Configuration

  • 100 character line width
  • Single quotes
  • Trailing commas
  • 2-space indentation

πŸ“š Test Data Management

Static Data (JSON)

const userData = DataGenerator.loadJsonFile('./src/test-data/userData.json');

Dynamic Data (Faker)

const email = DataGenerator.generateEmail();
const phone = DataGenerator.generatePhoneNumber();

Factory Pattern

const user = TestDataFactory.createUser({ name: 'John' });
const users = TestDataFactory.createUsers(5);

πŸ” Response Validation

Status Code

responseValidator.validateStatus(response.status, 200)

Response Body

responseValidator.validateBodyContent(actualBody, expectedBody)

Response Fields

responseValidator.validateBodyFields(body, ['id', 'name', 'email'])

Headers

responseValidator.validateHeaders(headers, { 'content-type': 'application/json' })

Response Time

responseValidator.validateResponseTime(responseTime, 5000)  // Max 5 seconds

Schema Validation

responseValidator.validateSchema(data, userSchema)

🧬 Test Isolation

Each test is independent with:

  • Fresh test data for each test
  • No data dependencies between tests
  • Setup/teardown for resource management
  • Clean fixture state
test.beforeEach(async ({ userClient }) => {
  // Before each test
});

test.afterEach(async ({ userClient }) => {
  // After each test
});

πŸ“ Logging Strategy

Logs are recorded for:

  • Request URL and method
  • Request headers and body
  • Response status and headers
  • Response body (first 500 chars)
  • Response time
  • Errors and stack traces

Log Levels:

  • error - Error messages
  • warn - Warning messages
  • info - General information
  • debug - Detailed debug information

Configure in .env:

LOG_LEVEL=info

πŸ”§ Troubleshooting

Tests Failing with Network Errors

// Increase timeout in playwright.config.ts
timeout: 30000

Retry Logic Not Working

// Check RETRY_ATTEMPTS and RETRY_DELAY in .env
RETRY_ATTEMPTS=3
RETRY_DELAY=1000

Token Expiration Issues

// Refresh token before tests
await authClient.refreshToken(refreshToken);

Port Already in Use

# Kill process on port 8080
lsof -ti:8080 | xargs kill -9

πŸ“š Additional Resources

🀝 Contributing

  1. Create a feature branch
  2. Write tests for new functionality
  3. Follow ESLint and Prettier rules
  4. Submit pull request

πŸ“„ License

MIT License - See LICENSE file for details

βœ… Checklist

Framework includes:

  • βœ… Clean architecture
  • βœ… Reusable components
  • βœ… Comprehensive logging
  • βœ… HTML reporting
  • βœ… Schema validation
  • βœ… Environment support
  • βœ… Token management
  • βœ… CI/CD integration
  • βœ… Error handling
  • βœ… Retry mechanism
  • βœ… Test isolation
  • βœ… Naming conventions
  • βœ… Security best practices
  • βœ… Scalability design
  • βœ… Parallel execution

πŸŽ“ Learning Path

  1. Start with user.spec.ts tests
  2. Understand UserClient implementation
  3. Learn ResponseValidator usage
  4. Create custom clients for your APIs
  5. Write comprehensive tests
  6. Configure CI/CD pipeline
  7. Monitor and optimize

Created with ❀️ for quality API testing

About

No description, website, or topics provided.

Resources

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors