API Automation using Playwright

Playwright is not limited to UI automation. In addition to browser-based testing, Playwright provides native support for API testing, which allows us to test backend APIs and frontend UI using the same test framework.

Playwright handles API testing using a built-in fixture called request. This fixture is automatically provided by Playwright and gives us access to an API request context, which can be used to send HTTP requests such as GET, POST, PUT, DELETE, and more.

Because this API testing capability is built into Playwright, we do not need any external libraries like Axios or SuperTest.

Using API automation in Playwright is especially useful for the following scenarios:

     - Creating test data quickly using APIs instead of slow UI flows
     - Validating backend APIs independently
     - Combining API and UI testing in the same test suite (for example, create data via API and verify it in UI)

In this section, we will learn how to handle API testing in Playwright using GET and POST requests with practical examples.

Example 1: GET Request

Scenario

Fetch a list of users from a public API and validate the response.

Example Code

import { test, expect } from '@playwright/test';
test('GET request example', async ({ request }) => {
    const response = await request.get('https://jsonplaceholder.typicode.com/users');
    // Display response status
    console.log('Status Code:', response.status());
    // Validate response status
    expect(response.status()).toBe(200);
    // Parse response body
    const responseBody = await response.json();
    // Display response body
    console.log(JSON.stringify(responseBody, null, 2));
    // Validate response data
    expect(responseBody.length).toBeGreaterThan(0);
    expect(responseBody[0]).toHaveProperty('id');
    expect(responseBody[0]).toHaveProperty('name');
});


Explanation

In this test, Playwright uses the built-in request fixture to send a GET request to the given API endpoint. The response returned from the request is an instance of APIResponse, which contains information such as the HTTP status code, response headers, and response body.

We first validate the HTTP status code to ensure the request was successful. Then we parse the response body using response.json() and validate the structure of the returned data.

Example 2: GET Request with Query Parameters

Scenario

Fetch posts specifically for User ID 1.

Example Code

import { test, expect } from '@playwright/test';
test('GET request with query parameters', async ({ request }) => {
    const response = await request.get('https://jsonplaceholder.typicode.com/posts', {
        params: {
            userId: 1
        }
    });
    // Display response status
    console.log('Status Code:', response.status());
    expect(response.ok()).toBeTruthy(); // Status code between 200 and 299
    const responseBody = await response.json();
    // Display response body
    console.log(JSON.stringify(responseBody, null, 2));
    // Validate that every post belongs to userId 1
    responseBody.forEach(post => {
        expect(post.userId).toBe(1);
    });
});


Explanation

In this example, we pass query parameters using the params option. Playwright automatically converts these parameters into a query string. The response.ok() method is a convenient shortcut that returns true when the HTTP status code is between 200 and 299.

Example 3: POST Request Using Playwright

Scenario

Create a new user using a POST API and validate the response.

Example Code

import { test, expect } from '@playwright/test';
test('POST request example', async ({ request }) => {
    const response = await request.post('https://jsonplaceholder.typicode.com/posts', {
        data: {
            title: 'Playwright API Test',
            body: 'This is a sample POST request',
            userId: 1
        }
    });
    // Display response status
    console.log('Status Code:', response.status());
    // Validate response status
    expect(response.status()).toBe(201);
    // Parse response body
    const responseBody = await response.json();
    // Display response body
    console.log(JSON.stringify(responseBody, null, 2));
    // Validate response data
    expect(responseBody.title).toBe('Playwright API Test');
    expect(responseBody.body).toBe('This is a sample POST request');
    expect(responseBody.userId).toBe(1);
});


Explanation

Here, we send a POST request with a request payload using the data property. Playwright automatically serializes the payload as JSON and sets the appropriate headers.

Note: JSONPlaceholder is a mock API, so the data is not actually saved on the server.

Playwright APIResponse Class

Whenever an API request is made using Playwright, it returns an object of type APIResponse.

Some commonly used methods of APIResponse are:

response.status() – returns the HTTP status code
response.ok() – returns true if the status code is 2xx
response.json() – parses and returns the response body as JSON
response.headers() – returns response headers

API Assertions in Playwright

Playwright’s expect assertion library can be used to validate API responses in the same way it is used for UI assertions, making API and UI testing consistent within the same framework.

 

Related Tutorials