3 minute read

Written by - Millan Kaul


๐Ÿš€ Type-Safe API Testing: A Playwright + TypeScript Framework


Building a fast, reliable and scalable API automation framework requires more than just writing tests. Itโ€™s about maintaining stability, enforcing best practices plus keeping everything developer-friendly.

Hereโ€™s how I scaled API testing using Playwright + TypeScript and structured a framework which -

โฆฟ Ran hundreds of API tests in 7.5 mins on GitHub pipelines. โฆฟ Used typed API responses for fail-safe assertions. โฆฟ Built short-commands in package.json scripts for smart test execution. โฆฟ Maintained a clear and easy-to-follow README file.


๐Ÿ›  Setting Up a Solid Playwright API Automation Framework

1๏ธโƒฃ Using TypeScript for API Response Validation

One of the biggest issues in API automation is unexpected API response changes. If a key is missing, null, or the data type changes, we must catch it early instead of debugging failures later.

Hereโ€™s how we map API responses to TypeScript interfaces and validate them:

Define a Type for API Response

โ€ Itโ€™s all about TYPEโ€™s if itโ€™s TypeScriptโ€ โ€” Unknown

export interface UserResponse {
  id: number;
  name: string;
  email: string;
  isActive: boolean;
}

Fetch & Validate Response Using Playwright

import { test, expect, request } from '@playwright/test';
import { UserResponse } from '../types/userTypes';

test('Validate API Response with TypeScript', async ({ request }) => {
    const response = await request.get('/api/users/1');
    expect(response.status()).toBe(200);

    // Parse response as JSON
    const responseBody: UserResponse = await response.json();

    // TypeScript will catch errors if response format changes
    expect(responseBody.id).toBeDefined();
    expect(typeof responseBody.name).toBe('string');
    expect(responseBody.email).toContain('@');
    expect(responseBody.isActive).toBeTruthy();
});

๐Ÿ”น Why? If id changes to a string or isActive becomes null, TypeScript will throw a type error before the test even runs. Less debugging, more confidence!


2๏ธโƒฃ Smart package.json Scripts for Flexible Test Runs

Instead of running complex CLI commands, we defined shortcuts in package.json:

package.json Script Configuration

"scripts": {
  "test": "npx playwright test",
  "smoke": "npx playwright test --grep @smoke",
  "regression": "npx playwright test --grep @regression",
  "login": "npx playwright test --grep @login",
  "critical": "npx playwright test --grep @critical",
  "api": "npx playwright test --grep @api",
  "report": "npx allure generate allure-results && npx allure open"
}

๐Ÿ’ก How This Helps?

  • ๐Ÿƒ Run only Smoke tests โ†’ npm run smoke
  • ๐Ÿš€ Trigger full regression โ†’ npm run regression
  • ๐Ÿ”ฅ Execute critical tests only โ†’ npm run critical
  • ๐Ÿ“Š Generate Allure report โ†’ npm run report

3๏ธโƒฃ Clear & Easy-to-Follow README.md

A good README ensures anyone (even in different time zones) can set up & run tests without confusion.

๐Ÿ“„ Sample README.md

# ๐Ÿš€ API Automation with Playwright & TypeScript  

Repository: http://github.com/qualitywithmillan

## ๐Ÿ“Œ Setup Instructions

### 1๏ธโƒฃ Install Dependencies
Ensure you have Node.js and npm installed:  
`npm install`

### 2๏ธโƒฃ Install Playwright
`npx playwright install`


### 3๏ธโƒฃ Run API Tests

| Command              | Description                        |
|----------------------|------------------------------------|
| `npm run test`       | Runs all tests                     |
| `npm run smoke`      | Runs smoke tests (@smoke)          |
| `npm run regression` | Runs full regression (@regression) |
| `npm run login`      | Runs login tests (@login)          |
| `npm run critical`   | Runs critical tests (@critical)    |
| `npm run report`     | Generates & opens Allure Report    |


### 4๏ธโƒฃ Viewing Reports
Run: `npm run report`

This will generate a "detailed Allure report" with test execution insights.  

## ๐Ÿ”— Need Help?
For any questions or issues, reach out via:  
๐Ÿ“ง Team Email: `team-support@example.com`
๐Ÿ’ฌ Slack Channel: `#api-automation`

---

### ๐Ÿ™ Thank You!
We appreciate your time in setting this up. Happy Testing! ๐Ÿš€  
#.github/workflows/playwright.yml
name: API Testing 

on:
  pull_request:
    branches: [ "main" ]

jobs:
  test:
    timeout-minutes: 60
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 18
      - name: Install dependencies
        run: npm install
      - name: Install Playwright Browsers
        run: npx playwright install --with-deps
      - name: Run all Playwright tests
        run: npx run test
      - uses: actions/upload-artifact@v3
        if: always()
        with:
          name: playwright-report
          path: playwright-report/

So, just by structuring API automation correctly, using TypeScript for type-safe API responses as well as leveraging smart scripts & documentation, we can:

โœ… Build a clean & stable framework. โœ… Ensure high reliability & developer trust.