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.
- β 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
- β 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
- β 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
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
- Node.js 18+
- npm or yarn
- Git
# Clone the repository
git clone <repository-url>
cd api-automation-framework
# Install dependencies
npm install
# Install Playwright browsers
npx playwright install# Copy environment template
cp .env.example .env
# Edit .env with your configuration
nano .envEnvironment 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=1000npm testnpm run test:uinpm run test:debugnpm run test:headednpm run test:parallelnpm run test:sequentialnpx playwright test src/tests/user.spec.tsnpx playwright test -g "User API Tests"# Generate HTML report
npm run test:reporter
# View HTML report
npm run report// Base client with retry logic and error handling
const userClient = new UserClient();
const response = await userClient.getUserById(1);// Generate test data dynamically
const user = TestDataFactory.createUser({
name: 'Custom Name'
});// Build complex requests fluently
const request = createRequestBuilder()
.addField('name', 'John')
.addField('email', 'john@example.com')
.withAuthToken(token);// Dependency injection in tests
test('test name', async ({ userClient, responseValidator, dataGenerator }) => {
// Use injected dependencies
});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);
});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);
});- Store sensitive data in
.envfile - Use environment variables for tokens/keys
- Rotate tokens regularly
- Validate SSL certificates
- Log without sensitive data
- Use HTTPS only in production
- Hardcode passwords or tokens
- Commit
.envfile to repository - Log sensitive information
- Use self-signed certificates
- Skip certificate validation
// Validate response time SLA
expect(responseValidator.validateResponseTime(responseTime, 3000)).toBe(true);npm run test:parallel # Uses 4 workers by default// Configurable in .env
RETRY_ATTEMPTS=3
RETRY_DELAY=1000 // milliseconds# 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
# Run with:
# - Matrix strategy for multiple environments
# - Artifact publishing
# - Test results reporting// Run with:
// - Parameter selection (environment, sequential/parallel)
// - Email notifications
// - Test result archivingnpm run lintnpm run type-checknpm run format- Strict TypeScript rules
- No implicit
any - No unused variables
- Single quotes required
- Semicolons required
- 100 character line width
- Single quotes
- Trailing commas
- 2-space indentation
const userData = DataGenerator.loadJsonFile('./src/test-data/userData.json');const email = DataGenerator.generateEmail();
const phone = DataGenerator.generatePhoneNumber();const user = TestDataFactory.createUser({ name: 'John' });
const users = TestDataFactory.createUsers(5);responseValidator.validateStatus(response.status, 200)responseValidator.validateBodyContent(actualBody, expectedBody)responseValidator.validateBodyFields(body, ['id', 'name', 'email'])responseValidator.validateHeaders(headers, { 'content-type': 'application/json' })responseValidator.validateResponseTime(responseTime, 5000) // Max 5 secondsresponseValidator.validateSchema(data, userSchema)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
});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 messageswarn- Warning messagesinfo- General informationdebug- Detailed debug information
Configure in .env:
LOG_LEVEL=info// Increase timeout in playwright.config.ts
timeout: 30000// Check RETRY_ATTEMPTS and RETRY_DELAY in .env
RETRY_ATTEMPTS=3
RETRY_DELAY=1000// Refresh token before tests
await authClient.refreshToken(refreshToken);# Kill process on port 8080
lsof -ti:8080 | xargs kill -9- Create a feature branch
- Write tests for new functionality
- Follow ESLint and Prettier rules
- Submit pull request
MIT License - See LICENSE file for details
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
- Start with
user.spec.tstests - Understand
UserClientimplementation - Learn
ResponseValidatorusage - Create custom clients for your APIs
- Write comprehensive tests
- Configure CI/CD pipeline
- Monitor and optimize
Created with β€οΈ for quality API testing