How To Test REST API In Playwright

Eugene Truuts
2 min readOct 28, 2023

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…

--

--

Eugene Truuts
Eugene Truuts

Written by Eugene Truuts

🇪🇪🇺🇸SDET at RingCentral, Inc. 👨🏻‍🎓B.Sc. in Computer Science. Talks about testing, automation, Playwright framework, JavaScript, GitLab, productivity,