Playwright Javascript Api Testing: Step-by-Step Guide (2026)

1. Introduction to Playwright JavaScript API Testing

API testing is an important part of modern software testing. It helps QA engineers verify whether an application communicates correctly with its backend services. Instead of testing everything through the user interface, testers can directly send HTTP requests and validate server responses.

Playwright JavaScript API testing allows automation engineers to test REST APIs using JavaScript and Playwright’s built-in API testing capabilities.

Playwright is widely known for browser automation, but it also provides powerful API testing features through APIRequestContext. Testers can perform GET, POST, PUT, PATCH, and DELETE operations, validate response status codes, check JSON data, and handle authentication.

For example, consider an employee management application. You can use Playwright to:

  • Retrieve employee information using GET requests.
  • Create a new employee using POST requests.
  • Update employee details using PUT or PATCH requests.
  • Delete employee records using DELETE requests.
  • Validate response status codes and JSON values.
  • Combine API testing with browser automation.

In this Playwright JavaScript API testing tutorial, we will build a practical API automation project from scratch. You will learn installation, API requests, authentication, assertions, test data management, debugging, and CI/CD integration.

2. What Is API Testing and Why Use Playwright?

API testing verifies the functionality, reliability, security, and performance-related behaviour of application programming interfaces.

An API acts as a communication layer between frontend applications and backend services.

For example, when a user logs into an application, the frontend sends login credentials to an authentication API. The backend validates those credentials and returns an appropriate response.

API testing verifies whether this communication works correctly.

Why Use Playwright for API Testing?

Playwright provides several advantages:

  1. JavaScript support: Write API automation scripts using familiar JavaScript syntax.
  2. Built-in assertions: Use Playwright’s expect() for response validation.
  3. Multiple HTTP methods: Support GET, POST, PUT, PATCH, and DELETE.
  4. Authentication: Configure authorization headers, tokens, and cookies.
  5. UI and API integration: Use API requests to prepare test data before browser testing.
  6. Test reporting: Generate HTML reports and debug failed tests.
  7. CI/CD integration: Execute API automation through GitHub Actions and Jenkins.

Unlike tools that focus exclusively on API testing, Playwright allows QA engineers to manage API and browser automation within one test framework.

3. Prerequisites and Playwright JavaScript Installation

Before starting Playwright JavaScript API testing, make sure you have the following:

  • Basic JavaScript knowledge.
  • Node.js and npm installed.
  • Visual Studio Code or another code editor.
  • Basic understanding of HTTP methods and REST APIs.

Step 1: Install Node.js

Download Node.js from:

https://nodejs.org

Verify the installation:

node -v

npm -v

Step 2: Create a Project

Create a project directory:

mkdir playwright-api-testing

cd playwright-api-testing

Initialize the Node.js project:

npm init -y

Step 3: Install Playwright Test

Install Playwright Test:

npm install -D @playwright/test

You do not need to install browser binaries for API-only tests because API testing does not require launching a browser.

Step 4: Create the Project Structure

Organize your files as follows:

playwright-api-testing/

│

├── tests/

│   ├── get-api.spec.js

│   ├── post-api.spec.js

│   └── crud-api.spec.js

│

├── playwright.config.js

├── package.json

└── .gitignore

This structure keeps API test cases organized and makes the project easier to maintain.

4. Understanding APIRequestContext and the Request Fixture

APIRequestContext is a Playwright class used to send HTTP requests directly to application APIs.

It supports different HTTP methods and provides response information for validation.

There are three commonly used approaches to creating API request contexts.

1. Using the Request Fixture

The request fixture is provided by Playwright Test.

const { test, expect } = require(‘@playwright/test’);

test(‘GET API example‘, async ({ request }) => {

    const response = await request.get(

        ‘https://jsonplaceholder.typicode.com/posts/1’

    );

    expect(response.status()).toBe(200);

});

The request fixture creates an isolated APIRequestContext for each test and automatically manages its lifecycle.

This is generally the easiest approach for beginners.

2. Using playwright.request.newContext()

You can create a standalone API request context when you need more control over configuration.

const { test, expect } = require(‘@playwright/test’);

test(‘Standalone API context’, async ({ playwright }) => {

    const apiContext = await playwright.request.newContext({

        baseURL: ‘https://jsonplaceholder.typicode.com’

    });

    const response = await apiContext.get(‘/posts/1’);

    expect(response.status()).toBe(200);

    await apiContext.dispose();

});

Remember to dispose of manually created contexts after completing API requests.

3. Using Browser Context Requests

Playwright also supports:

page.request

This API request context shares cookies with the associated browser context. It is useful when browser and API tests need to share authentication sessions.

For most independent API testing scenarios, the request fixture is sufficient.

5. Sending GET, POST, PUT, PATCH, and DELETE Requests

Let’s understand the five commonly used HTTP methods with practical JavaScript examples.

For these examples, we will use JSONPlaceholder, a public fake REST API:

https://jsonplaceholder.typicode.com

GET Request

GET retrieves information from a server.

const { test, expect } = require(‘@playwright/test’);

test(‘Verify GET API’, async ({ request }) => {

    const response = await request.get(‘/posts/1’);

    expect(response.status()).toBe(200);

    const responseBody = await response.json();

    expect(responseBody.id).toBe(1);

    expect(responseBody.userId).toBe(1);

    console.log(responseBody);

});

POST Request

POST creates a new resource.

test(‘Verify POST API’, async ({ request }) => {

    const response = await request.post(‘/posts’, {

        data: {

            title: ‘Playwright API Testing,

            body: ‘Learning API automation,

            userId: 1

        }

    });

    expect(response.status()).toBe(201);

    const responseBody = await response.json();

    expect(responseBody.title)

        .toBe(‘Playwright API Testing’);

});

PUT Request

PUT generally replaces an existing resource.

test(‘Verify PUT API’, async ({ request }) => {

    const response = await request.put(‘/posts/1’, {

        data: {

            id: 1,

            title: ‘Updated Playwright,

            body: ‘Updated API testing content,

            userId: 1

        }

    });

    expect(response.status()).toBe(200);

    const body = await response.json();

    expect(body.title).toBe(‘Updated Playwright’);

});

PATCH Request

PATCH updates selected fields of an existing resource.

test(‘Verify PATCH API’, async ({ request }) => {

    const response = await request.patch(‘/posts/1’, {

        data: {

            title: ‘Partially Updated Title’

        }

    });

    expect(response.status()).toBe(200);

    const body = await response.json();

    expect(body.title)

        .toBe(‘Partially Updated Title’);

});

DELETE Request

DELETE removes a resource.

test(‘Verify DELETE API’, async ({ request }) => {

    const response = await request.delete(‘/posts/1’);

    expect(response.status()).toBe(200);

});

Note: JSONPlaceholder simulates write operations. These examples validate the returned responses but do not permanently modify its underlying database.

6. Validating Status Codes, Headers, and JSON Responses

Sending API requests is not enough. A good automation test must validate the response.

Playwright supports different assertions through expect().

Validate Status Code

expect(response.status()).toBe(200);

Validate Response Headers

const headers = response.headers();

expect(headers[‘content-type’])

    .toContain(‘application/json’);

Validate JSON Response Body

const body = await response.json();

expect(body.id).toBe(1);

expect(body.title).toBeTruthy();

expect(body.userId).toBe(1);

Validate Multiple Response Conditions

test(‘Validate API response’, async ({ request }) => {

    const response = await request.get(‘/posts/1’);

    expect(response.ok()).toBeTruthy();

    expect(response.status()).toBe(200);

    const body = await response.json();

    expect(body).toHaveProperty(‘id’);

    expect(body).toHaveProperty(‘title’);

    expect(body).toHaveProperty(‘body’);

});

These assertions help identify missing fields, incorrect data, and unexpected server responses.

7. API Authentication and Request Headers

Many real-world APIs require authentication before accessing protected endpoints.

Common authentication methods include:

  • Bearer token authentication.
  • Basic authentication.
  • API key authentication.
  • Cookie-based authentication.

Bearer Token Authentication Example

test(‘Verify authenticated API’, async ({ request }) => {

    const response = await request.get(‘/users/me’, {

        headers: {

            Authorization: `Bearer ${process.env.API_TOKEN}`,

            Accept: ‘application/json’

        }

    });

    expect(response.status()).toBe(200);

});

Store your token in an environment variable instead of writing sensitive credentials directly inside test files.

For a reusable configuration, you can create a separate API context:

const { test, expect } = require(‘@playwright/test’);

test(‘API authentication’, async ({ playwright }) => {

    const apiContext = await playwright.request.newContext({

        baseURL: ‘https://api.example.com’,

        extraHTTPHeaders: {

            Authorization: `Bearer ${process.env.API_TOKEN}`,

            Accept: ‘application/json’

        }

    });

    const response = await apiContext.get(‘/users/me’);

    expect(response.status()).toBe(200);

    await apiContext.dispose();

});

Replace the example endpoint and token with valid application credentials.

8. Reusing API Requests and Managing Test Data

In enterprise test automation, writing the same API request repeatedly creates maintenance problems.

A better approach is to create reusable API methods.

For example, create an apiHelper.js file:

class ApiHelper {

    constructor(request) {

        this.request = request;

    }

    async getPost(id) {

        return await this.request.get(`/posts/${id}`);

    }

    async createPost(data) {

        return await this.request.post(‘/posts’, {

            data

        });

    }

    async updatePost(id, data) {

        return await this.request.put(`/posts/${id}`, {

            data

        });

    }

    async deletePost(id) {

        return await this.request.delete(`/posts/${id}`);

    }

}

module.exports = { ApiHelper };

Now reuse these methods inside your test cases:

const { test, expect } = require(‘@playwright/test’);

const { ApiHelper } = require(‘../apiHelper’);

test(‘Reusable API helper test, async ({ request }) => {

    const api = new ApiHelper(request);

    const response = await api.getPost(1);

    expect(response.status()).toBe(200);

});

This approach reduces duplicate code and supports better test framework design.

For real applications, use unique test data, environment-specific configuration, and cleanup operations to prevent test interference.

9. Combining API Testing with UI Automation

One important advantage of Playwright is that API testing and UI automation can work together. Consider an employee management application. Before testing the employee dashboard, you may need to create an employee account. Instead of manually filling out a registration form every time, create the employee through an API request.

const { test, expect } = require(‘@playwright/test’);

test(‘Create employee through API and verify UI’, async ({

    request,

    page

}) => {

    const response = await request.post(‘/employees’, {

        data: {

            name: ‘Rahul’,

            department: ‘Testing’

        }

    });

    expect(response.status()).toBe(201);

    const employee = await response.json();

    await page.goto(‘/employees’);

    await expect(

        page.getByText(employee.name)

    ).toBeVisible();

});

This example assumes the application provides the employee endpoint and a matching UI.

Benefits of Combining API and UI Testing

  1. Faster test data preparation.
  2. Reduced dependency on repetitive UI actions.
  3. Better end-to-end test coverage.
  4. Easier validation of backend and frontend behaviour.
  5. Improved regression testing efficiency.

You can also perform UI actions first and then use API requests to verify whether the backend stored the expected information.

10. Complete Real-World Playwright JavaScript API Testing Project

Let’s combine the concepts into a small API automation project.

Step 1: Configure Playwright

Create playwright.config.js:

const { defineConfig } = require(‘@playwright/test’);

module.exports = defineConfig({

    testDir: ‘./tests’,

    timeout: 30000,

    reporter: ‘html’,

    use: {

        baseURL: ‘https://jsonplaceholder.typicode.com’,

        extraHTTPHeaders: {

            Accept: ‘application/json’

        }

    }

});

Step 2: Create API Test Cases

Create tests/crud-api.spec.js:

const { test, expect } = require(‘@playwright/test’);

test.describe(‘Playwright API Testing‘, () => {

    test(‘GET – Retrieve post’, async ({ request }) => {

        const response = await request.get(‘/posts/1’);

        expect(response.status()).toBe(200);

        const body = await response.json();

        expect(body.id).toBe(1);

        expect(body.title).toBeTruthy();

    });

    test(‘POST – Create post’, async ({ request }) => {

        const response = await request.post(‘/posts’, {

            data: {

                title: ‘API Automation,

                body: ‘Testing with Playwright,

                userId: 1

            }

        });

        expect(response.status()).toBe(201);

        const body = await response.json();

        expect(body.title).toBe(‘API Automation’);

    });

    test(‘PUT – Update post’, async ({ request }) => {

        const response = await request.put(‘/posts/1’, {

            data: {

                id: 1,

                title: ‘Updated Post’,

                body: ‘Updated Content’,

                userId: 1

            }

        });

        expect(response.status()).toBe(200);

        const body = await response.json();

        expect(body.title).toBe(‘Updated Post’);

    });

    test(‘PATCH – Update title’, async ({ request }) => {

        const response = await request.patch(‘/posts/1’, {

            data: {

                title: ‘Patch Updated’

            }

        });

        expect(response.status()).toBe(200);

        const body = await response.json();

        expect(body.title).toBe(‘Patch Updated’);

    });

    test(‘DELETE – Delete post’, async ({ request }) => {

        const response = await request.delete(‘/posts/1’);

        expect(response.status()).toBe(200);

    });

});

Step 3: Execute API Tests

Run all test cases:

npx playwright test

Run a specific test:

npx playwright test tests/crud-api.spec.js

Run tests with a list of available tests:

npx playwright test –list

The HTML report can be opened using:

npx playwright show-report

You now have a basic working Playwright JavaScript API testing project.

11. Reporting, Debugging, and CI/CD Integration

Reporting and debugging are important parts of professional automation frameworks.

Generate HTML Reports

Configure the reporter in playwright.config.js:

reporter: [

    [‘list’],

    [‘html’, { open: ‘never’ }]

]

After execution, use:

npx playwright show-report

Debug API Tests

Use console logging to understand API responses:

const response = await request.get(‘/posts/1’);

console.log(‘Status:’, response.status());

console.log(‘Body:’, await response.json());

For more detailed debugging, Playwright also supports test traces and test execution debugging options.

GitHub Actions Integration

Create this file:

.github/workflows/playwright.yml

name: Playwright API Tests

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

jobs:

  api-tests:

    runs-on: ubuntu-latest

    steps:

      – name: Checkout Repository

        uses: actions/checkout@v6

      – name: Setup Node.js

        uses: actions/setup-node@v6

        with:

          node-version: lts/*

      – name: Install Dependencies

        run: npm ci

      – name: Run API Tests

        run: npx playwright test

      – name: Upload HTML Report

        if: ${{ !cancelled() }}

        uses: actions/upload-artifact@v5

        with:

          name: playwright-report

          path: playwright-report/

          retention-days: 30

This workflow executes API tests automatically whenever developers push changes or create pull requests targeting the main branch.

For Jenkins, you can configure a pipeline with Node.js installation, dependency installation, Playwright test execution, and report publishing stages.

12. Common Errors and Troubleshooting

ErrorPossible Solution
401 UnauthorizedCheck API token and authentication headers.
403 ForbiddenVerify user permissions.
404 Not FoundCheck the API endpoint and resource ID.
500 Internal Server ErrorInvestigate backend logs and request data.
Timeout errorCheck network connectivity and API response time.
Invalid JSON responseVerify response format before parsing JSON.
Module not foundInstall dependencies and check import paths.

Best Practices for Playwright JavaScript API Testing

13. Frequently Asked Questions

1. What is Playwright JavaScript API testing?

Playwright JavaScript API testing is a testing approach that uses Playwright’s APIRequestContext to send HTTP requests and validate REST API responses using JavaScript.

2. How do I get started with Playwright JavaScript API testing?

Install Node.js, create a project, install @playwright/test, configure a base URL, and start writing API tests using the request fixture.

3. Is Playwright JavaScript API testing suitable for beginners?

Yes. Beginners with basic JavaScript and HTTP knowledge can quickly learn API testing using Playwright. Its built-in request fixture and assertions make API automation easier.

4. Can Playwright test REST APIs?

Yes. Playwright supports REST API testing through GET, POST, PUT, PATCH, and DELETE requests.

5. What is APIRequestContext in Playwright?

APIRequestContext is an API provided by Playwright for sending HTTP requests, configuring headers, managing cookies, and validating server responses.

6. Can Playwright perform API and UI testing together?

Yes. You can create test data through APIs, verify application behaviour through the browser, and validate backend results after UI interactions.

7. Is Playwright API testing free?

Playwright is an open-source automation framework. Its API testing functionality is available through the Playwright Test package without requiring a separate API testing subscription.

Leave a Comment

Your email address will not be published. Required fields are marked *