paint-brush
Testing REST API In Playwrightby@truuts
158 reads

Testing REST API In Playwright

by Eugene TruutsOctober 30th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Playwright is a web testing tool you use for frontend testing. Sometimes your tests need to interact with some APIs, for example, to get test data from the server. In this brief guide, you will learn how to test API with Playwright built-in tools.
featured image - Testing REST API In Playwright
Eugene Truuts HackerNoon profile picture


Although Playwright is the web testing tool you use for frontend testing, sometimes your tests need to interact with some APIs, for example, to get test data from the server. For example, it can be an authorization token or something else you want to get and use during the test.

In this brief guide, you will learn how to test API with Playwright built-in tools, including request sending and response parsing.


One of the pros of using the Playwright framework is its ability to work with REST API smoothly without using third-party libraries such as node-fetch. All you need to send requests is the built-in APIRequest class introduced in Playwright v1.16.


This class is used for creating APIRequestContext instances, which can be used for sending web requests. An instance of this class can be obtained via playwright.request:

const context = await request.newContext();


I will use the “reqres.in” service for this guide, which simulates real application scenarios for testing purposes.


Since you’ve added a context for the API requests, introduce the response constant to store the APIResponce. Don’t forget to use the correct HTTP method (POST, GET, PUT, etc). The APIRequest supports any of them.

const response = await context.post('https://reqres.in/api/users', {
        data: {
            "name": "Eugene Truuts",
            "job": "SDET"
        },
        headers: {
            "accept": "application/json"
        }
    });


And then, store its answer in the new “responseJson” constant:

const responseJson = await response.json();


For example, let’s check if the response status code is 201:

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


I suggest also adding a custom error message with the additional response information that can be useful in debugging and makes your test reports a little bit more readable:

expect(response.status(), {
    message: `Invalid code ${response.status()} - ${await response.text()}]`,
}).toEqual(200);


After we have checked the response status, we can parse the response object using the JSON.stringify() method and use this parsed data in further test logic. For instance, let’s check that user ID was defined in response:

const userId = JSON.stringify(responseJson.id);
    expect(userId, {
        message: `No user ID in response - ${await response.text()}]`,
    }).toBeDefined()You can also get the different response properties, such as headers, body, status, and others, which you can use in test assertions.


The complete test example:

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

const API_BASE_URL = 'https://reqres.in';
const HTTP_RESPONSE = {
    OK: 200,
    CREATED: 201
}

test('POST request example test', async () => {
    const context = await request.newContext();
    const response = await context.post(`${API_BASE_URL}/api/users`, {
        data: {
            "name": "Eugene Truuts",
            "job": "SDET"
        },
        headers: {
            "accept": "application/json"
        }
    });
    const responseJson = await response.json();
    console.log(JSON.stringify(`New user added: ${responseJson.name}, ID: ${responseJson.id}`));
    expect(response.status(), {
        message: `Invalid code ${response.status()} - ${await response.text()}]`,
    }).toEqual(HTTP_RESPONSE.CREATED);
    const userId = JSON.stringify(responseJson.id);
    expect(userId, {
        message: `No user ID in response - ${await response.text()}]`,
    }).toBeDefined()
});

In this lesson, you have learned how to send API requests using Playwright and read the response using JSON.stringify(). Happy testing!


Also published here.