How to Test REST APIs Using Playwright


If you are learning automation testing, you will eventually work with REST APIs.

A REST API exposes endpoints that applications use to retrieve, create, update, and delete information. Testing those endpoints is an important part of validating modern applications.

With Playwright, you can perform REST API testing using its API request capabilities without opening a browser for every test.

This guide takes a practical approach and walks through the main HTTP operations step by step.

What Is REST API Testing?

REST API testing verifies that REST endpoints behave according to their expected contract.

Imagine a task-management application with endpoints such as:

GET    /api/tasks

POST   /api/tasks

PUT    /api/tasks/101

PATCH  /api/tasks/101

DELETE /api/tasks/101


A tester can verify whether each operation returns the expected status code and data.

REST APIs commonly use JSON to exchange information between the client and server.

Step 1: Set Up Playwright

If you are starting a Playwright project, install Playwright Test using your Node.js project setup.

For an existing project, Playwright can be installed with:

npm init playwright@latest


During setup, choose the JavaScript or TypeScript configuration that matches your project.

A typical API test imports test and expect:

import { test, expect } from '@playwright/test';


The built-in request fixture can then be used to make API requests.

Step 2: Test a GET Request

Let's start with a simple task retrieval API.

import { test, expect } from '@playwright/test';


test('Get task details', async ({ request }) => {

  const response = await request.get('/api/tasks/101');


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


  const task = await response.json();


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

});


What is happening?

The test performs four basic actions:

  1. Sends a GET request.

  2. Waits for the response.

  3. Checks the HTTP status.

  4. Reads and validates the JSON body.

A successful response does not always mean the complete test is correct. Important response properties should also be checked.

Step 3: Send a POST Request

POST requests are commonly used to create new resources.

test('Create a task', async ({ request }) => {

  const response = await request.post('/api/tasks', {

    data: {

      title: 'Learn Playwright API testing',

      completed: false

    }

  });


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


  const task = await response.json();


  expect(task.title).toBe('Learn Playwright API testing');

});


The data object represents the request payload.

Playwright supports passing serializable data directly to request methods and can serialize object data as JSON when appropriate.

Step 4: Test a PUT Request

PUT is commonly used when replacing or updating a resource.

test('Update task using PUT', async ({ request }) => {

  const response = await request.put('/api/tasks/101', {

    data: {

      title: 'Updated Playwright task',

      completed: true

    }

  });


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


  const task = await response.json();


  expect(task.completed).toBe(true);

});


The exact status code depends on the API contract. Do not assume every PUT endpoint must return the same code.

Step 5: Test a PATCH Request

PATCH is generally used for a partial update.

For example, suppose the task already has several properties but you only want to change its completion status.

test('Update task status', async ({ request }) => {

  const response = await request.patch('/api/tasks/101', {

    data: {

      completed: true

    }

  });


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


  const task = await response.json();


  expect(task.completed).toBe(true);

});


The advantage is that the request can update only the fields required by the API.

Step 6: Test a DELETE Request

DELETE is used to remove a resource.

test('Delete task', async ({ request }) => {

  const response = await request.delete('/api/tasks/101');


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

});


A DELETE endpoint may return 204 No Content, but the expected response depends on the API design.

For that reason, API tests should be written against the application's documented contract rather than assumptions.

Step 7: Use Query Parameters

Many REST APIs use query parameters for filtering, searching, pagination, or sorting.

For example:

/api/tasks?status=completed


In Playwright:

test('Filter completed tasks', async ({ request }) => {

  const response = await request.get('/api/tasks', {

    params: {

      status: 'completed'

    }

  });


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


  const tasks = await response.json();


  expect(Array.isArray(tasks)).toBe(true);

});


Playwright's request methods support a params option for query parameters.

Step 8: Add Request Headers

Headers provide additional information to the server.

For example:

const response = await request.get('/api/profile', {

  headers: {

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

    Accept: 'application/json'

  }

});


You may use headers for:

  • Authorization

  • Content type

  • Accept type

  • Correlation IDs

  • Custom application headers

Never put a real API token directly into your test file.

Step 9: Test Path Parameters

A path parameter identifies a specific resource.

For example:

/api/users/205


Here, 205 is the user ID.

In Playwright:

const userId = 205;


const response = await request.get(`/api/users/${userId}`);


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


This makes your test reusable.

Step 10: Test Authenticated APIs

Authentication is common in real REST API testing.

One approach is to obtain a token through an authentication endpoint and use it in later requests.

For example:

const token = process.env.API_TOKEN;


const response = await request.get('/api/orders', {

  headers: {

    Authorization: `Bearer ${token}`

  }

});


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


Playwright also supports authentication workflows where API authentication state can be saved and reused.

For security:

  • Store secrets outside the source code.

  • Use environment variables.

  • Protect CI/CD secrets.

  • Never commit authentication state containing live credentials.

Understanding HTTP Status Codes

Your API tests should verify the status codes expected by the API contract.

Status

Common meaning

200

Successful request

201

Resource created

204

Successful request with no response body

400

Bad request

401

Authentication required/failed

403

Access forbidden

404

Resource not found

500

Server-side error

These meanings are common HTTP conventions, but your test should always follow the documented behavior of the specific API.

Validating JSON Responses

Checking the status code alone is not enough.

Suppose the API returns:

{

  "id": 101,

  "title": "Learn Playwright",

  "completed": false

}


You can validate individual properties:

const data = await response.json();


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

expect(data.title).toBe('Learn Playwright');

expect(data.completed).toBe(false);


You can also check that required fields exist:

expect(data).toHaveProperty('id');

expect(data).toHaveProperty('title');


CRUD Testing With Playwright

CRUD means:

  • Create — POST

  • Read — GET

  • Update — PUT/PATCH

  • Delete — DELETE

A complete workflow could look like this:

POST → Create task

  ↓

GET → Retrieve task

  ↓

PUT/PATCH → Update task

  ↓

GET → Verify update

  ↓

DELETE → Remove task


This is a useful way to think about REST API coverage.

However, individual automated tests should generally avoid unnecessary dependencies on other tests. A test that requires another test to run first can become difficult to maintain.

Real-World Example

Consider a learning platform.

A tester may need to verify:

POST /api/students


creates a student.

Then:

GET /api/students/{id}


returns the student.

Next:

PATCH /api/students/{id}


updates the student's course.

Finally:

DELETE /api/students/{id}


removes the test record.

The important part is not just sending requests. The tester should validate status codes, response properties, error behavior, authentication, and business rules.

Common REST API Testing Mistakes

Testing only successful scenarios

Negative cases are important.

Test situations such as:

  • Missing required fields

  • Invalid IDs

  • Unauthorized requests

  • Expired tokens

  • Invalid data types

Hardcoding test data

Hardcoded values can cause conflicts between environments.

Hardcoding secrets

Never commit passwords or tokens.

Ignoring response bodies

A successful HTTP response may still contain incorrect application data.

Making every test dependent

Independent tests are easier to rerun and debug.

Best Practices

For maintainable Playwright REST API testing:

  • Use reusable request configuration.

  • Keep authentication secure.

  • Use environment-specific configuration.

  • Validate meaningful response properties.

  • Test positive and negative scenarios.

  • Give tests descriptive names.

  • Keep test data controlled.

  • Avoid unnecessary test dependencies.

  • Add API tests to CI/CD.

  • Use reporting to identify failures quickly.

For learners building a larger automation framework, you can connect REST API testing with Playwright fixtures, Page Object Model concepts, and Playwright projects as your framework grows.

Frequently Asked Questions

How do I test a REST API using Playwright?

Use Playwright's API request capabilities, send HTTP requests such as GET or POST, then validate the status code, response headers, JSON body, and expected business behavior.

How do I send a GET request in Playwright?

Use:

const response = await request.get('/api/users');


You can add query parameters through the params option.

How do I send a POST request?

Use:

await request.post('/api/users', {

  data: {

    name: 'Test User'

  }

});


Can Playwright test authenticated APIs?

Yes. Authentication headers, tokens, cookies, and reusable authentication state can be used depending on the application.

Can Playwright perform CRUD testing?

Yes. GET, POST, PUT/PATCH, and DELETE requests can be combined to validate CRUD behavior.

Featured-Snippet Answer

To test a REST API using Playwright, create or use an API request context, send HTTP requests such as GET, POST, PUT, PATCH, and DELETE, and validate status codes, headers, JSON responses, authentication, and expected business behavior.

Conclusion

Playwright REST API testing provides a practical way to automate backend validation using the same ecosystem many teams already use for browser automation.

Start with simple GET and POST requests. Then add PUT, PATCH, DELETE, authentication, query parameters, response validation, negative scenarios, and CRUD workflows.

As your framework matures, combine API testing with UI testing instead of treating them as separate worlds.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

Playwright Multiple Tabs and Windows Explained: A Practical Guide