Playwright Masters

Playwright API Testing: Complete Guide With Examples, Authentication, CRUD & Best Practices

Playwright API testing allows testers and developers to test backend APIs directly using Playwright without opening a browser.

Instead of clicking buttons and waiting for a webpage to load, you can send an API request, receive the response, and check whether the result is correct.

For example:

A user clicks Login on a website.

Table of Contents

The browser sends a login request to an API.

The API checks the username and password.

The API returns a response.

If the API is broken, the login page may also fail.

With Playwright API testing, you can test that backend communication directly.

Playwright provides APIRequestContext for sending HTTP(S) requests and validating API behavior. It can also be used together with browser tests, making it possible to create test data through an API, test the same data through the UI, and then verify the backend state again.

In simple words:

Playwright API testing = Send API request → Receive response → Validate the response → Report the result.

This guide explains Playwright API testing from beginner to advanced level with practical examples.

Playwright API Testing

What Is Playwright API Testing?

Playwright API testing is the process of using Playwright’s APIRequestContext to send HTTP requests directly to an API and verify its response.

You can test:

  • GET requests
  • POST requests
  • PUT requests
  • PATCH requests
  • DELETE requests
  • HTTP status codes
  • Response bodies
  • JSON data
  • Headers
  • Authentication
  • Cookies
  • Query parameters
  • Path parameters
  • API workflows
  • Error responses
  • REST APIs
  • GraphQL APIs
  • UI + API workflows

Playwright API tests can run using the same Playwright Test runner used for browser automation.

This is one of Playwright’s biggest advantages for automation engineers because you do not necessarily need a separate framework just to perform API checks.

Why Is API Testing Important?

Imagine an online shopping website.

You search for a product.

The page looks perfect.

But behind the page, the API returns the wrong price.

The website may still load successfully.

A UI-only test might say:

Test Passed

But the customer could see the wrong price.

API testing checks the data behind the screen.

An API test can verify:

Request

   ↓

API Server

   ↓

Response

   ↓

Status Code

   ↓

Headers

   ↓

Response Body

   ↓

Assertions

   ↓

PASS / FAIL

 

This allows problems to be discovered before they become visible to users.

How Does Playwright API Testing Work?

Playwright provides an APIRequestContext.

Think of it as a small API client inside your Playwright test.

For example:

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

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

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

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

});

Here:

  • request is Playwright’s API request fixture.
  • get() sends a GET request.
  • response contains the server response.
  • status() returns the HTTP status code.
  • expect() verifies the result.

The important point is that no browser page is required for this API request.

The official Playwright documentation describes APIRequestContext as the API used for Web API testing and explains that it can also prepare server-side state for end-to-end tests.

Playwright API Testing vs UI Testing

UI testing interacts with what the user sees.

API testing interacts directly with the backend.

UI testing

 

Open browser

Open website

Click Login

Enter username

Enter password

Click button

Check dashboard

 

API testing

 

Send login request

Receive response

Check status

Check token

Check user data

 

API testing is often faster because it does not need to load the complete user interface.

However, API testing should not completely replace UI testing.

A strong automation strategy usually combines both.

How to Set Up Playwright for API Testing

If Playwright is not installed, create a Playwright project.

npm init playwright@latest

 

Choose JavaScript or TypeScript during setup.

For professional Playwright projects, TypeScript is a popular choice because it provides type checking and better editor support.

After installation, you can create an API test file such as:

tests/

   api/

      users.spec.ts

      login.spec.ts

      products.spec.ts

 

You can also define a common API URL in playwright.config.ts.

Example:

import { defineConfig } from ‘@playwright/test’;

 

export default defineConfig({

  use: {

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

  }

});

 

Now your tests can use relative paths:

await request.get(‘/users’);

 

instead of repeatedly writing:

await request.get(‘https://api.example.com/users’);

 

This makes the framework easier to maintain.

Your First Playwright API Test

Let’s create a simple GET request.

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

 

test(‘should get users’, async ({ request }) => {

 

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

 

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

 

});

 

The test performs three simple steps:

  1. Send the request.
  2. Receive the response.
  3. Check the status code.

But professional API testing should not stop at the status code.

A server can return:

200 OK

 

and still send incorrect data.

Therefore, validate the response body as well.

How to Read a JSON Response

Suppose the API returns:

{

  “id”: 101,

  “name”: “Ravi”,

  “email”: “ravi@example.com”

}

You can read the JSON response:

const body = await response.json();

console.log(body);

Then validate individual values:

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

expect(body.name).toBe(‘Ravi’);

expect(body.email).toBe(‘ravi@example.com’);

A strong API test checks the meaning of the response, not just whether the server responded.

Testing GET APIs With Playwright

GET requests are normally used to retrieve information.

Example:

test(‘should get a user’, async ({ request }) => {

 

  const response = await request.get(‘/users/101’);

 

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

 

  const body = await response.json();

 

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

  expect(body.name).toBe(‘Ravi’);

 

});

 

You can also test query parameters.

For example:

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

  params: {

    page: 2,

    limit: 10

  }

});

 

This is cleaner than manually constructing the URL.

Testing POST APIs With Playwright

POST requests are commonly used to create new data.

For example, creating a user:

test(‘should create a user’, async ({ request }) => {

 

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

    data: {

      name: ‘Ravi’,

      email: ‘ravi@example.com’

    }

  });

 

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

 

  const body = await response.json();

 

  expect(body.name).toBe(‘Ravi’);

  expect(body.email).toBe(‘ravi@example.com’);

 

});

 

A good POST test should verify:

  • Status code
  • Response body
  • Important returned fields
  • Generated ID
  • Headers when relevant
  • Business rules
  • Error conditions

Testing PUT APIs

  • PUT is commonly used to replace an existing resource or update its data.

    Example:

    test(‘should update user’, async ({ request }) => {


      const response = await request.put(‘/users/101’, {

        data: {

          name: ‘Ravi Kumar’,

          email: ‘ravi.kumar@example.com’

        }

      });


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


    });


    Do not assume PUT and PATCH mean the same thing.

    A useful rule is:

    PUT = full replacement

    PATCH = partial update

    The exact behavior depends on the API contract, so always follow the API specification.

Testing PATCH APIs

PATCH is normally used to update only selected fields.

test(‘should update only user name’, async ({ request }) => {

 

  const response = await request.patch(‘/users/101’, {

    data: {

      name: ‘Ravi Kumar’

    }

  });

 

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

 

});

 

This is helpful when you only need to modify specific parts of an existing resource.

Testing DELETE APIs

DELETE is used to remove a resource.

test(‘should delete user’, async ({ request }) => {

 

  const response = await request.delete(‘/users/101’);

 

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

 

});

 

The expected status code depends on the API contract.

Some APIs return:

  • 200 OK
  • 202 Accepted
  • 204 No Content

Do not blindly expect one status code for every DELETE endpoint.

Playwright API Assertions

Assertions are one of the most important parts of API testing.

A weak test might only check:

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

 

A stronger test checks several layers.

Status

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

 

Success

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

 

Response body

const body = await response.json();

 

expect(body.name).toBe(‘Ravi’);

 

Response header

expect(response.headers()[‘content-type’])

  .toContain(‘application/json’);

 

The goal is not to create hundreds of assertions.

The main purpose is to confirm that the important values are correct.

How to Test API Error Responses

Professional API testing must test failures too.

Do not test only:

200 = success

Test:

  • Invalid login
  • Missing required field
  • Invalid token
  • Expired token
  • Invalid ID
  • Duplicate data
  • Unauthorized request
  • Forbidden request
  • Server errors
  • Invalid JSON
  • Incorrect parameters

For example:

test(‘should reject invalid user data’, async ({ request }) => {

 

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

    data: {

      name: ”

    }

  });

 

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

 

});

 

A reliable API should continue to work properly even when something goes wrong.

A reliable API also handles incorrect input correctly.

Playwright API Authentication

Authentication is one of the most important topics in real-world API automation.

Common authentication methods include:

  • Bearer tokens
  • API keys
  • Basic authentication
  • Cookies
  • OAuth-based flows

For a bearer token:

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

  headers: {

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

  }

});

 

Do not hard-code real tokens in your test files.

Bad:

Authorization: ‘Bearer my-real-secret-token’

 

Better:

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

 

Store secrets in environment variables or your CI/CD secret manager.

Using API Authentication to Prepare UI Tests

This is where Playwright API testing becomes especially powerful.

Imagine your UI test needs a logged-in customer.

Instead of:

Open website

Enter username

Enter password

Click login

Wait

Continue test

 

you can sometimes authenticate through the API first.

API Login

Create authentication state

Open browser

Continue directly to application

 

This can reduce unnecessary UI work.

Playwright also supports sharing API request state with browser contexts in appropriate configurations. The official documentation explains that BrowserContext.request and Page.request use the browser context’s cookie storage, while a separately created API request context can have isolated cookie storage.

APIRequestContext in Playwright

There are two important approaches.

1. Playwright request fixture

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

 

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

 

});

 

This is usually the easiest approach inside a Playwright test.

2. Standalone APIRequestContext

You can also create an isolated API request context.

import { request } from ‘@playwright/test’;

 

const apiContext = await request.newContext({

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

});

 

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

 

await apiContext.dispose();

 

The official APIRequest documentation supports creating an APIRequestContext using request.newContext().

Playwright API Testing With Fixtures

As a project becomes larger, repeating authentication and configuration becomes messy.

Fixtures can help.

For example:

import { test as base } from ‘@playwright/test’;

 

export const test = base.extend({

 

  api: async ({ request }, use) => {

 

    await use(request);

 

  }

 

});

 

A real project can use custom fixtures for:

  • Authentication
  • API clients
  • Test data
  • Database setup
  • Environment configuration
  • Reusable API helpers

This makes the framework easier to maintain.

For more framework architecture, see the [Playwright Framework guide].

Combining UI and API Testing

One of the strongest Playwright API testing strategies is:

API + UI + API

For example, an e-commerce test can work like this:

API

Create test customer

API

Create product

UI

Open website

Add product to cart

UI

Complete checkout

API

Verify order

 

This is much closer to a real business workflow.

The official Playwright API testing documentation specifically describes using APIs to prepare server-side state before visiting the application and to validate server-side conditions after browser actions.

Playwright API Testing With CRUD

CRUD means:

  • C — Create
  • R — Read
  • U — Update
  • D — Delete

The normal mapping is:

CRUD

HTTP Method

Playwright

Create

POST

request.post()

Read

GET

request.get()

Update

PUT/PATCH

request.put() / request.patch()

Delete

DELETE

request.delete()

A complete CRUD test might look like:

Create user

Verify user created

Get user

Verify user details

Update user

Verify updated data

Delete user

Verify deletion

 

This is a valuable project for anyone learning Playwright API automation.

Testing REST APIs With Playwright

Playwright can test REST APIs because it can send HTTP(S) requests through APIRequestContext.

You can test:

GET /users

POST /users

GET /users/101

PUT /users/101

PATCH /users/101

DELETE /users/101

 

REST API testing with Playwright is particularly useful when your team already uses Playwright for UI automation.

Can Playwright Test GraphQL APIs?

Yes.

GraphQL normally uses requests containing a query in the request body.

For example:

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

  data: {

    query: `

      query {

        users {

          id

          name

        }

      }

    `

  }

});

 

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

 

Playwright is not limited to traditional REST endpoints.

Checkly’s current Playwright API testing guide demonstrates API testing with GraphQL and notes that Playwright can also test HTTP-based REST APIs.

Playwright API Mocking vs API Testing

These two concepts are often confused.

API testing

You call the real API.

Playwright

Real API

Real response

Assertion

 

API mocking

You replace or intercept the API response.

Playwright

Intercept request

Mock response

UI validation

 

Mocking is useful when you want to test frontend behavior without depending on a live backend.

For example:

API returns 500

Does the UI show an error message?

 

Or:

API returns empty array

Does the UI show “No products found”?

 

Playwright supports network interception and response mocking through its routing capabilities.

When Should You Use Playwright API Testing?

Playwright API testing is especially useful when:

1. You already use Playwright

You can keep UI and API automation in the same ecosystem.

2. You need fast test data setup

Create data through an API instead of using many UI clicks.

3. You want to verify backend state

After a UI action, verify the server directly.

4. You need API smoke tests

Quickly check whether important endpoints are working.

5. You need end-to-end workflows

Combine API preparation with browser actions.

6. You need authentication setup

Use API requests to prepare authenticated state where appropriate.

When Is a Dedicated API Tool Better?

Playwright is powerful, but it is not automatically the best choice for every API testing project.

If your team needs extensive:

  • API documentation
  • Contract management
  • Schema-first workflows
  • Large API collections
  • Specialized API test management
  • Dedicated API collaboration features

then a specialized API platform may be useful.

For example, Apidog emphasizes API scenarios, schema-based workflows and API-focused testing capabilities.

The important lesson is:

Choose the tool based on the testing problem, not because one tool is popular.

If your organization already uses Playwright heavily, keeping API and UI automation together can be a major advantage.

Best Practices for Playwright API Testing

Follow these practices when building professional API automation.

1. Validate more than status codes

A 200 response does not automatically mean the data is correct.

Check the important response fields too.

2. Keep secrets outside source code

Use environment variables and CI/CD secrets.

3. Use a base URL

Avoid repeating long API URLs throughout your test files.

4. Create reusable API helpers

If the same API operation is used repeatedly, create reusable functions.

5. Generate unique test data

Avoid relying on the same hard-coded email or username in every run.

6. Clean up test data

If a test creates records, remove them when appropriate.

7. Test negative scenarios

Test invalid inputs and authorization failures.

8. Keep tests independent

One failed test should not unnecessarily break unrelated tests.

9. Use meaningful test names

Bad:

test1

 

Better:

should reject login with invalid password

 

10. Run API tests in CI/CD

API tests are excellent candidates for automated pipelines.

Playwright API Testing in CI/CD

A professional automation project should not depend only on a developer’s laptop.

A common pipeline looks like:

Developer pushes code

        ↓

Git

        ↓

CI/CD Pipeline

        ↓

Install dependencies

        ↓

Run Playwright API tests

        ↓

Run UI tests

        ↓

Generate report

        ↓

PASS / FAIL

 

You can integrate Playwright with tools such as:

  • GitHub Actions
  • Jenkins
  • Azure Pipelines
  • GitLab CI
  • Other CI/CD platforms

This allows API problems to be detected automatically after code changes.

How to Organize a Playwright API Testing Framework

For a larger project, you can organize API automation like this:

playwright-project/

 

├── tests/

│   ├── api/

│   │   ├── users.spec.ts

│   │   ├── login.spec.ts

│   │   └── orders.spec.ts

│   │

│   └── ui/

│       ├── login.spec.ts

│       └── checkout.spec.ts

├── api/

│   ├── users.ts

│   ├── orders.ts

│   └── auth.ts

├── fixtures/

│   └── api-fixtures.ts

├── test-data/

├── utils/

├── playwright.config.ts

└── package.json

 

Do not copy this structure blindly.

A small project should remain simple.

A large enterprise project can use a more structured architecture.

The best framework is the one that remains understandable as the number of tests grows.

Common Playwright API Testing Mistakes

Mistake 1: Checking only 200

A successful status code does not prove that the response is correct.

Mistake 2: Hard-coding tokens

Never place production credentials directly in Git.

Mistake 3: Using production data carelessly

API tests can create, update and delete real data.

Use dedicated test environments whenever possible.

Mistake 4: Ignoring negative testing

Real users do not always provide perfect input.

Mistake 5: Creating dependent tests

Avoid making Test B work only because Test A happened to run first.

Mistake 6: Testing only APIs

APIs are important, but the complete user experience still needs UI and end-to-end testing.

Mistake 7: Overengineering the framework

Do not create 30 helper classes for five API tests.

Start simple and add structure when the project needs it.

Playwright API Testing vs Postman

A common question is:

Can Playwright replace Postman?

The answer is: sometimes, but not always.

Postman is primarily designed around API development, exploration and collaboration.

Playwright is a broader automation framework that can combine:

UI Testing

+

API Testing

+

End-to-End Testing

+

Network Mocking

+

Browser Automation

 

If your main goal is exploring APIs manually, a dedicated API tool may be more convenient.

If your goal is automated UI + API + end-to-end testing in one codebase, Playwright can be an excellent choice.

Playwright API Testing Learning Path

If you are a beginner, do not start with advanced API architecture.

Follow this order:

  1. HTTP Basics

        ↓

  1. GET / POST / PUT / PATCH / DELETE

        ↓

  1. JSON

        ↓

  1. Status Codes

        ↓

  1. Headers

        ↓

  1. Query Parameters

        ↓

  1. Authentication

        ↓

  1. Playwright request fixture

        ↓

  1. API Assertions

        ↓

  1. CRUD Testing

        ↓

  1. API + UI Testing

        ↓

  1. Fixtures

        ↓

  1. API Mocking

        ↓

  1. Test Data

        ↓

  1. CI/CD

        ↓

  1. Real-Time API Automation Framework

 

This approach is easier for beginners because every new concept builds on the previous one.

For a broader Playwright learning path, see the [Playwright Roadmap] and [Playwright Syllabus].

Real-World Playwright API Testing Example

Imagine an online shopping application.

A complete automated scenario could be:

API Login

Get authentication token

Create test customer

Create product

Open website

Search product

Add product to cart

Checkout

API: Get order

Verify order amount

Verify customer

Verify order status

Clean test data

 

This is much closer to how automation works in real engineering teams.

You are not simply testing whether a button can be clicked.

You are testing whether the complete business process works.

Why Learn Playwright API Testing?

Playwright API testing is valuable because modern applications depend heavily on APIs.

A website may have:

  • Frontend
  • Backend
  • Authentication service
  • Payment API
  • Product API
  • Order API
  • Database
  • Third-party integrations

Testing only the visible webpage does not give complete confidence.

API automation lets you test the communication between these systems.

For automation engineers, learning both UI and API testing can also help you design stronger end-to-end frameworks.

If you are learning Playwright professionally, you can explore the [Playwright Framework guide] and the [Playwright course syllabus].

Final Takeaway

Playwright API testing is a powerful way to automate backend API validation using the same Playwright ecosystem used for modern web testing.

You can use Playwright to:

  • Send GET requests
  • Send POST requests
  • Update data with PUT
  • Partially update data with PATCH
  • Delete resources
  • Validate status codes
  • Validate JSON responses
  • Validate headers
  • Test authentication
  • Test REST APIs
  • Test GraphQL APIs
  • Create test data
  • Verify backend state
  • Combine API and UI testing
  • Mock network responses
  • Build reusable fixtures
  • Run tests in CI/CD

The biggest advantage is not simply that Playwright can send an HTTP request.

The real advantage is the ability to combine:

API + UI + End-to-End + Automation Framework + CI/CD

in one modern testing ecosystem.

If you are learning Playwright, do not learn API testing as an isolated topic.

Learn how API testing connects with:

Locators → Assertions → Fixtures → Authentication → UI Testing → Framework Development → CI/CD

That is how you move from writing simple Playwright scripts to building professional automation frameworks.

Frequently Asked Questions About Playwright API Testing

What is Playwright API testing?

Playwright API testing is the process of sending HTTP(S) requests using Playwright’s APIRequestContext and validating the responses returned by an API.

Does Playwright support API testing?

Yes. Playwright provides APIRequestContext for API testing. It can send HTTP(S) requests and can also be used to prepare or verify server-side state during end-to-end testing.

Can Playwright test REST APIs?

Yes. Playwright can send HTTP requests such as GET, POST, PUT, PATCH and DELETE, making it suitable for REST API automation.

Can Playwright test GraphQL APIs?

Yes. GraphQL requests can be sent using Playwright’s API request functionality. The request body can contain the GraphQL query and variables.

Does Playwright API testing require a browser?

No. API tests using the request fixture can send API requests without opening a browser.

What is APIRequestContext in Playwright?

APIRequestContext is Playwright’s API client interface for sending HTTP(S) requests and working with API responses. It can be created independently or associated with a browser context.

What is the Playwright request fixture?

The request fixture provides an API request context inside Playwright tests.

Example:

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

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

});

 

Can Playwright test API authentication?

Yes. You can send authentication information through headers, cookies and other supported request options. For sensitive credentials, use environment variables or secure CI/CD secrets.

Can Playwright test API response JSON?

Yes.

const body = await response.json();

 

expect(body.name).toBe(‘Ravi’);

 

Can Playwright perform CRUD API testing?

Yes. You can use POST for creating resources, GET for reading them, PUT/PATCH for updates and DELETE for removing resources.

Can Playwright combine API and UI testing?

Yes. This is one of the most useful Playwright workflows. You can create data through an API, interact with it through the UI and then validate the backend state through another API request.

Is Playwright good for API testing?

Playwright is particularly useful when your team already uses Playwright for UI and end-to-end testing because API and browser automation can live in the same testing ecosystem.

For API-only teams with extensive API management requirements, a specialized API platform may sometimes be a better fit.

Can Playwright replace Postman?

It can replace some automated API testing workflows, but Playwright and Postman solve somewhat different problems. Playwright is especially valuable when API tests need to work together with UI and end-to-end automation.

What Is the Best Way to Learn Playwright API Testing?

Start with HTTP basics, REST APIs, JSON, status codes, request methods, authentication and assertions. Then learn Playwright’s request fixture, CRUD automation, API/UI integration, fixtures, mocking and CI/CD.

Where can I learn Playwright automation testing?

You can explore the [Playwright Masters Playwright Automation Testing course] for a broader curriculum covering UI automation, API testing, framework development, authentication, CI/CD and real-time projects.

Playwright Masters automation testing logo - White Back ground

Playwright Masters Team

Playwright Automation Testing Experts | Industry-Focused Training & Practical Learning

Playwright Masters is a dedicated automation testing training platform focused on helping learners build practical skills in Playwright automation testing. Our training covers real-world automation concepts, framework practices, coding, debugging, API testing, cross-browser testing, CI/CD, and interview preparation to help learners develop job-ready testing skills.

Scroll to Top