Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Playwright TypeScript API Testing Framework Setup

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through building a maintainable API testing framework using Playwright and TypeScript. You'll end up with a structured project that separates test logic, API clients, and configuration, making it easy to add new tests, handle authentication, and run tests in CI. The framework uses Playwright's built-in request context, which means you don't need extra HTTP libraries, and TypeScript gives you type safety across your test suite.

What You'll Need

  • Node.js 16 or later installed on your machine
  • A code editor (VS Code recommended)
  • Basic familiarity with TypeScript and REST APIs
  • An API endpoint to test (you can use a public test API like JSONPlaceholder)

Step-by-Step

  1. Initialize the project Create a new directory and run npm init -y to generate a package.json file.
  2. Install dependencies Run npm install -D @playwright/test typescript @types/node. This installs Playwright's test runner, TypeScript, and Node.js type definitions.
  3. Set up TypeScript configuration Create a tsconfig.json file with the following settings:
    {
      "compilerOptions": {
        "target": "ES2022",
        "module": "commonjs",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
      },
      "include": ["tests", "src", "playwright.config.ts"]
    }
  4. Create the Playwright configuration Create playwright.config.ts at the root. This file tells Playwright where tests are, sets the base URL for your API, and configures reporters. Here's a minimal config:
    import { defineConfig } from '@playwright/test';
    
    export default defineConfig({
      testDir: './tests',
      timeout: 30000,
      use: {
        baseURL: 'https://jsonplaceholder.typicode.com',
        extraHTTPHeaders: {
          'Content-Type': 'application/json',
        },
      },
      reporter: [['list'], ['html', { open: 'never' }]],
    });
  5. Create a folder structure Create the following directories: tests for test files, src/api for API client classes, src/models for TypeScript interfaces, and src/utils for helpers.
  6. Define data models In src/models, create a file user.ts with an interface that represents the data you'll work with. For example:
    export interface User {
      id: number;
      name: string;
      email: string;
    }
  7. Build an API client Create src/api/BaseClient.ts that wraps Playwright's request fixture. This class will handle common methods like GET, POST, PUT, DELETE, and also handle authentication if needed. Here's a basic version:
    import { APIRequestContext } from '@playwright/test';
    
    export class BaseClient {
      constructor(protected request: APIRequestContext) {}
    
      async get(path: string) {
        const response = await this.request.get(path);
        return response;
      }
    
      async post(path: string, data?: object) {
        const response = await this.request.post(path, { data });
        return response;
      }
    
      // Similar for put, patch, delete
    }
  8. Create specific API endpoints For each resource, create a class that extends BaseClient. For example, src/api/UsersClient.ts:
    import { BaseClient } from './BaseClient';
    import { User } from '../models/user';
    
    export class UsersClient extends BaseClient {
      async getAll(): Promise {
        const response = await this.get('/users');
        return response.json();
      }
    
      async getById(id: number): Promise {
        const response = await this.get(`/users/${id}`);
        return response.json();
      }
    }
  9. Write your first test Create tests/users.spec.ts. Use Playwright's test and expect. The request fixture is available in each test, so you can instantiate your client:
    import { test, expect } from '@playwright/test';
    import { UsersClient } from '../src/api/UsersClient';
    
    test.describe('Users API', () => {
      test('GET /users returns a list of users', async ({ request }) => {
        const usersClient = new UsersClient(request);
        const users = await usersClient.getAll();
        expect(Array.isArray(users)).toBeTruthy();
        expect(users.length).toBeGreaterThan(0);
      });
    
      test('GET /users/1 returns a single user', async ({ request }) => {
        const usersClient = new UsersClient(request);
        const user = await usersClient.getById(1);
        expect(user.id).toBe(1);
        expect(user.name).toBeDefined();
      });
    });
  10. Run the tests Add a script to package.json: "test": "playwright test". Then run npm test. You should see the tests pass.
  11. Add authentication support If your API requires a token, modify the BaseClient to accept a token and set it in the headers. You can also use Playwright's globalSetup to fetch a token once and store it in a file or environment variable.
  12. Create a fixture for the client To avoid repeating instantiation in every test, create a custom fixture in src/fixtures.ts:
    import { test as base } from '@playwright/test';
    import { UsersClient } from './api/UsersClient';
    
    export const test = base.extend<{ usersClient: UsersClient }>({
      usersClient: async ({ request }, use) => {
        const client = new UsersClient(request);
        await use(client);
      },
    });
    Then import test from this file in your tests instead of from @playwright/test.
  13. Add environment configuration Use dotenv to manage environment-specific variables like base URL and API keys. Install dotenv, create a .env file, and load it in the Playwright config.
  14. Organize tests with groups Use test.describe blocks to group related tests. Use tags like @smoke or @regression to selectively run tests with --grep.
  15. Add reporting and CI integration Playwright's HTML reporter is great for local debugging. For CI, you can use the JSON or JUnit reporter to integrate with your CI tool. Add a ci script that runs tests with the appropriate reporter.

Common Mistakes

  • Not separating API clients from tests – This leads to duplication and makes maintenance harder.
  • Hardcoding URLs and credentials – Use environment variables and the baseURL config.
  • Ignoring status codes – Always assert on the HTTP status code, not just the body content.
  • Not handling authentication properly – Don't log in for every test; use a shared token or a setup step.
  • Overusing test data – Avoid creating the same data in every test; use fixtures or setup scripts.

Tips

  • Use TypeScript interfaces for all API responses to catch errors at compile time.
  • Create helper functions for common assertions (e.g., expectSuccess).
  • Use Playwright's request fixture directly for one-off requests, but use client classes for repeated patterns.
  • Keep your test files small and focused on one resource or workflow.
  • Use test.beforeAll to set up data that is shared across tests in a describe block.
  • Run tests in parallel by default; ensure your tests are independent.

Troubleshooting

  • Tests fail with 404 errors – Check your baseURL and the path in your client. Make sure the API is reachable.
  • TypeScript compilation errors – Run npx tsc --noEmit to see errors. Ensure your tsconfig includes the right files.
  • Tests hang or timeout – Increase the timeout in the config, or check if your API is slow. Also make sure you're not accidentally using a browser context instead of request context.
  • Authentication fails – Verify that your token is being sent correctly. Use or set it in extraHTTPHeaders .
  • Tests pass locally but fail in CI – Ensure environment variables are set in CI. Use a .env.example file to document needed variables.

Frequently Asked Questions

Do I need a browser for API testing?

No. Playwright's request fixture uses Node.js's HTTP client, so no browser is launched. This makes tests fast and lightweight.

How do I handle dynamic data like timestamps?

Use a library like faker to generate random data, or compute values inside the test. Avoid hardcoding values that change.

Can I reuse the same token across tests?

Yes. Use a globalSetup file to fetch a token once and store it in a file or environment variable that tests read.

How do I run only a subset of tests?

Use --grep to filter by test name, or use tags. For example: npx playwright test --grep "@smoke".

What's the best way to structure test data?

Create a separate data folder with JSON or TypeScript objects. Use factories to generate unique data per test run.

How do I integrate this with CI/CD?

Install Playwright browsers in your CI image, run npm ci and npm test. Use the JUnit reporter to get results in a format your CI tool understands.