Playwright API Testing Tutorial: Complete Beginner’s Guide with TypeScript Examples

Introduction

Playwright API Testing Tutorial is one of the most searched topics among QA automation engineers because Playwright is no longer limited to UI automation. It also provides powerful built-in support for testing REST APIs using TypeScript. This means you can automate backend testing without relying on external libraries.

If you are a Selenium engineer, manual tester, software testing student, or interview candidate, learning Playwright API Testing can significantly improve your automation skills. In this guide, you’ll learn how to perform API testing using Playwright, understand enterprise framework concepts, and build reusable API automation tests with practical TypeScript examples.


What is Playwright API Testing?

Playwright API Testing is the process of sending HTTP requests and validating API responses using Playwright’s built-in APIRequestContext.

Instead of opening a browser, Playwright communicates directly with the server, making API tests much faster than UI tests.

With Playwright, you can:

  • Test REST APIs
  • Validate JSON responses
  • Verify status codes
  • Perform CRUD operations
  • Test authentication
  • Chain multiple API requests
  • Combine API and UI automation in one framework

This makes Playwright API Automation an excellent choice for modern software testing.


Why Use Playwright for API Testing?

Playwright offers several advantages over traditional API testing tools.

Benefits

  • Built-in API testing support
  • Excellent TypeScript integration
  • Fast execution
  • Simple assertions
  • Authentication support
  • Parallel execution
  • HTML reporting
  • CI/CD integration
  • One framework for both UI and API testing

Because of these features, many organizations use Playwright as their primary Playwright API Framework.


Setting Up Playwright for API Testing

Step 1: Create a New Project

mkdir PlaywrightAPIFramework

cd PlaywrightAPIFramework

Step 2: Initialize the Project

npm init -y

Step 3: Install Playwright

npm init playwright@latest

Choose:

  • TypeScript
  • Playwright Test
  • Install browsers

After installation, your project is ready for API automation.


HTTP Methods in Playwright API Testing

GET Request Example

GET is used to retrieve data from the server.

import { test, expect } from ‘@playwright/test’;

test(‘Get User Details’, async ({ request }) => {

    const response = await request.get(

        ‘https://reqres.in/api/users/2’

    );

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

});

Explanation

  • request.get() sends a GET request.
  • The response is stored in the response object.
  • expect(response.status()).toBe(200) verifies that the API returned a successful response.

POST Request Example

POST creates a new resource.

test(‘Create User’, async ({ request }) => {

    const response = await request.post(

        ‘https://reqres.in/api/users’,

        {

            data: {

                name: ‘John’,

                job: ‘QA Engineer’

            }

        }

    );

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

});

Explanation

  • The data object contains the request payload.
  • Playwright automatically converts it into JSON.
  • Status code 201 confirms successful resource creation.

PUT Request Example

PUT replaces an existing resource.

test(‘Update User’, async ({ request }) => {

    const response = await request.put(

        ‘https://reqres.in/api/users/2’,

        {

            data: {

                name: ‘Peter’,

                job: ‘Automation Tester’

            }

        }

    );

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

});


PATCH Request Example

PATCH updates specific fields instead of replacing the complete resource.

test(‘Patch User’, async ({ request }) => {

    const response = await request.patch(

        ‘https://reqres.in/api/users/2’,

        {

            data: {

                job: ‘Senior QA Engineer’

            }

        }

    );

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

});


DELETE Request Example

DELETE removes an existing resource.

test(‘Delete User’, async ({ request }) => {

    const response = await request.delete(

        ‘https://reqres.in/api/users/2’

    );

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

});

A 204 No Content response indicates that the resource was deleted successfully.


Request Headers, Query Parameters, and Authentication

Sending Request Headers

const response = await request.get(

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

    {

        headers: {

            Authorization: ‘Bearer your_access_token’,

            Accept: ‘application/json’

        }

    }

);

Headers are commonly used for authentication and content negotiation.


Query Parameters

const response = await request.get(

    ‘https://reqres.in/api/users’,

    {

        params: {

            page: 2,

            per_page: 5

        }

    }

);

Query parameters allow you to filter, search, or paginate API results.


Bearer Authentication

Many enterprise applications secure APIs using Bearer tokens.

headers: {

    Authorization: ‘Bearer eyJhbGciOi…’

}

Always store tokens securely using environment variables instead of hardcoding them.


API Response Validation and Assertions

Validating only the status code is not enough. You should also verify the response body.

test(‘Validate User Response’, async ({ request }) => {

    const response = await request.get(

        ‘https://reqres.in/api/users/2’

    );

    const body = await response.json();

    expect(body.data.first_name).toBe(‘Janet’);

    expect(body.data.id).toBe(2);

});

Explanation

  • response.json() converts the API response into a JavaScript object.
  • The assertions verify that the correct user information is returned.
  • This ensures the API behaves as expected.

Enterprise API Framework Folder Structure

A clean project structure makes API automation easier to maintain.

PlaywrightAPIFramework

├── api

│     UserAPI.ts

│     LoginAPI.ts

├── tests

│     user.spec.ts

│     login.spec.ts

├── fixtures

│     apiFixture.ts

├── utils

│     TokenManager.ts

├── test-data

│     users.json

├── config

│     environment.ts

└── playwright.config.ts

Folder Explanation

  • api – Contains reusable API methods.
  • tests – Stores test scenarios.
  • fixtures – Reusable setup code.
  • utils – Helper methods and token management.
  • test-data – Stores JSON request payloads.
  • config – Environment-specific configuration.

This architecture is commonly used in enterprise-level Playwright API Frameworks.


Best Practices

Follow these best practices for successful Playwright REST API Testing:

  • Keep API methods reusable.
  • Store URLs in configuration files.
  • Use environment variables for tokens.
  • Validate both status codes and response bodies.
  • Store request payloads in JSON files.
  • Use meaningful assertions.
  • Keep tests independent.
  • Follow consistent naming conventions.
  • Log request and response details for debugging.
  • Use HTML reports.
  • Run tests in parallel.
  • Integrate with CI/CD pipelines.
  • Handle negative test scenarios.
  • Avoid duplicate code.
  • Organize your project with a scalable folder structure.

Common Mistakes

Avoid these common mistakes:

  • Hardcoding API tokens.
  • Checking only status codes.
  • Ignoring response body validation.
  • Mixing API logic with test logic.
  • Using duplicate request code.
  • Not testing error responses.
  • Keeping all tests in one file.
  • Ignoring reusable helper methods.

Real-Time API Testing Scenarios

Scenario 1: Login API

  • Send login request.
  • Validate access token.
  • Store token for future API calls.

Scenario 2: User Management

  • Create a user.
  • Retrieve user details.
  • Update the user.
  • Delete the user.
  • Verify successful deletion.

Scenario 3: E-commerce Application

Login API

      │

      ▼

Product API

      │

      ▼

Cart API

      │

      ▼

Checkout API

      │

      ▼

Order API

This workflow is commonly automated in enterprise applications.


Playwright API Testing Interview Questions

1. What is Playwright API Testing?

Testing REST APIs using Playwright’s built-in API request capabilities.

2. What is APIRequestContext?

It is the Playwright object used to send HTTP requests.

3. Which HTTP methods does Playwright support?

GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.

4. Why use Playwright for API automation?

It combines UI and API testing within the same framework.

5. What is REST API testing?

Testing APIs that communicate using HTTP methods and JSON data.

6. What is the difference between PUT and PATCH?

PUT replaces an entire resource, while PATCH updates only selected fields.

7. How do you validate an API response?

By checking status codes, response headers, response time, and JSON data.

8. What is Bearer Authentication?

A token-based authentication method commonly used for REST APIs.

9. Can Playwright perform UI and API testing together?

Yes. API calls can create test data before running UI tests.

10. How do you build a scalable Playwright API Framework?

By separating API services, tests, fixtures, utilities, configuration, and test data into dedicated folders.


FAQs

Is Playwright good for API testing?

Yes. It provides built-in support for REST API automation with TypeScript.

Does Playwright support TypeScript?

Yes. TypeScript is fully supported and recommended.

Can Playwright replace Postman?

Playwright is excellent for API automation. Postman remains useful for manual API exploration and debugging.

Is Playwright API testing fast?

Yes. API tests execute much faster than browser-based UI tests because they communicate directly with the server.

Can Playwright test authenticated APIs?

Yes. It supports Basic Authentication, Bearer tokens, OAuth flows, and custom headers.

Can API and UI tests be combined?

Yes. Many organizations use API calls to prepare test data before running UI automation.

Is Playwright suitable for beginners?

Yes. Its simple syntax and excellent documentation make it beginner-friendly.

Can Playwright integrate with CI/CD?

Yes. It integrates with Jenkins, GitHub Actions, Azure DevOps, GitLab CI, and other CI/CD tools.

Leave a Comment

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