Playwright, renowned for its UI Testing prowess, is also a formidable tool for API automation. This blog delves into how to harness Playwright’s capabilities for efficient API testing, providing practical examples and insights into its key features.
Why use Playwright for API testing
Unified Testing Ecosystem: Playwright’s versatility allows seamless testing of both web interfaces and APIs within a single framework, streamlining workflows and enhancing efficiency.
Comprehensive API Interaction: Playwright offers robust tools for interacting with APIs, enabling you to confidently test API endpoints and validate responses.
Cross-Browser API Reliability: Ensure consistent API performance across different browsers through Playwright’s comprehensive cross-browser testing capabilities.
Let’s Start with Simple Example in Playwriter API
Installation and configuration
Prerequisite
- Node (version>17)
- NPM
- Visual Studio Code
Installation
Create one project Folder and run below command from the command prompt on the project root folder. Install Playwright using following command
npm init playwright
Configuration
Open the project folder in VS code
We can See Folder Structure in Below Manner.

We can see it created one playwright.config.js.In playwright.config.js we can customize various aspect of the test, we can say that it is centralised location to define setting, option and configuration.In this we will update the value of the base url for our project.I am using https://restful-booker.herokuapp.com/apidoc/index.html for the API Automation.

Link for the Above pic https://gist.github.com/shikha814223/2f52ad3a98de23e4d1f1738c96226996
First API Test
Let’s Start our API automation in TypeScript. In Playwright For constructing the API request, we need Playwright’s APIRequestContext.
- APIRequestContext isolates API calls for each test, ensuring independent execution and preventing cross-contamination of API interactions. Each test receives its own APIRequestContext instance, allowing HTTP requests to be made without impacting other tests.
- The first request which we will see is GET Request.
GET Request

link->https://gist.github.com/shikha814223/0f89fb9bf24143413d47e97776733d45
- Importing ‘test’ and ‘expect’ from playwright, ‘test’ is the test runner and ‘expect’ help to do assertions
- Create a test method, with name “create get api test’, which takes ‘request’ as input. ‘request’ here is APIRequestContext instance automatically provided by Playwright takes a request object responsible for making HTTP requests.
- It sends a GET request to the API endpoint /booking/1 and waits for a response.
Assert that the status of an HTTP response is 200, for a successful request.Parses response body as JSON and stores it in responseBody. - Assert that the response body contains the field firstname, lastname and total price.
POST Request
Now let’s see POST API request, verifying its success by examining the status code, and delving into validating JSON API responses.

https://gist.github.com/shikha814223/e9c220152438bed287785ec9a6b79194.js
- A test case is defined using Playwright’s test function, called ‘create post api’ test using static request body.
- Inside this test, we create a constant object called requestBody which consists of the data that will be sent to the API.
- This has fields like firstname, lastname, totalprice, depositpaid and another one nested inside it called bookingdates that contains checkin and checkout.
- Further down there is an additional field added named additional needs which is set at “Breakfast”.
- This test then sends a POST request at the endpoint of /booking by means of request.post() passing in requestBody as data for its payload. It will wait for any response from this API call and store that in response variable.
- By console.log (await response. Json()); the test logs out JSON body of response to console log which comes handy during debugging process to understand what does API return.
- Thus finally what happens next are checks made by this test on HTTP status code of response being 200 implying successful request was made by it. Also check whether or not this response is OK i.e expect(response.ok()).toBeTruthy() which means that status falls within range of 200 – 299.
- Subsequently, it asserts if some fields exist in the response body so as not only to confirm a properly created booking but also ensure that properties of firstname and lastname have been assigned with values within booking object returned in response.
API test using Fixtures
What are Fixtures in Playwright?
Playwright offers built-in fixtures for common setup and teardown tasks, fixtures provide isolated environments for each test, ensuring they have all necessary resources and nothing extra.
Fixture helps in reducing the common step and provide all the
Example:
Browser Fixture: This fixture can be used to launch a new browser instance before each test and close it afterward.
Page Fixture: Each test runs in its own isolated environment, created by the page fixture, which includes a new browser context and page.
Test Fixture: The test info fixture supplies details and metadata about the currently executing test.
Why it is important?
Fixtures are arguably the most powerful tool in API testing; they are easy to maintain and provide test isolation and ensure consistencies. Fixtures mean centralizing common tasks, such as the structure of dependencies used, the data-creation process, and lean setup for the test.
Consistency: Shared state dependencies are removed, ensuring the consistent execution of tests. Reusable fixtures help to eliminate redundancy in writing codes related to the testing and give an extra edge on the time taken on test execution.
Flexibility: The option of adding parameters makes the fixture flexible and solves any different testing scenarios.
Maintainability: Modular design, together with clean code, will enhance readability and maintainability of tests.
Scalability: The fixtures can handle complicated dependencies in large test suite setups.
Fixture system by Playwright also includes a built-in mechanism for the dependency management, making it easy to inject the required fixtures for tests, and serves for automatic resolution. This feature also adds simplicity to the process of reusing setup code across multiple tests.
API Test
API Base Class

https://gist.github.com/shikha814223/b4497fae90daa4c9d2c4e7394f4cf895.js
- A class is defined encapsulating API request related function.APIRequestContext is the type of property request in it.
- In the constructor it takes an object of APIRequestContext and assigns it to the class property request, enabling HTTP requests to be made by this class using Playwright’s request context.
- To send HTTP requests, sendRequest is a reusable function which has parameters: endpoint as the api endpoint to send request to, method as the type of HTTP method like GET, POST etc that you want to use, optional reqBody parameter being an empty object by default and optional accessToken for authentication that is a string with no characters by default.
- Headers and request body are contained in requestOptions object.
- You send the request dynamically (GET, POST etc.) using this.request[method]() and return the response.
- This is a convenience function calling sendRequest with either HTTP POST or GET method only having two arguments i.e endpoint and optional request body (reqBody).
Fixture Class.
Creating our test fixture is easy.
https://gist.github.com/shikha814223/12530bf6dd1807c72f86ed09539b9725.js
- A single property API of type APIBase is created using TypeScript type alias named APIFixture. This type defines what additional properties shall be available during tests inside the test context.
- This method test.extend is used to extend Playwright’s test object with custom fixture. This way objects that are reusable (in this case an instance of API) can be injected into tests.
- Define API fixture: API property is declared as a fixture having an asynchronous initialization. The fixture creates another instance based on APIBase using request provided by Playwright itself; such request is helpful when making HTTP requests in tests.
- Call await use(apiInstance): By using ‘use’, it allows other tests to utilize apiInstance which is always passed down into the test environment and this function allows you to do so.
- Export the fixtures: Fixtures object containing extended logic for tests are exported from this file so that they will have access to all these imported objects in their own files.
API Test Class

https://gist.github.com/shikha814223/5881257c176d78f92650182d061c5f8e.js
- This set of test is called the “API Demo test suits,” which were constructed with the help of test.describe() function. There are two variable: token – an identity token retrieved from the authorization interface, and booking ID – which will store booking id for the further use.
- beforeAll Hook: Runs once before all tests. Sends a POST request to the /auth endpoint with a username and password. Extracts the token from the response and stores it for future requests.
- In Test [GET] Retrieve list of bookings and verify response, sends a GET request to the /booking endpoint to retrieve a list of bookings. Uses expect.soft() to verify the response status is 200 and response JSON contains the property bookingid.
- Sends a POST request to the /booking endpoint with the booking details (e.g., firstname, lastname, totalprice, bookingdates). Validating the response status is 200. Verify the response JSON contains the property bookingid, and store it into BookingId variable for future purposes.
Conclusion
Although Playwright is best known as a UI-testing tool, it’s also very powerful for API automation. This means you can test web interfaces and APIs in a single framework, which simplifies your workflows. Features like APIRequestContext that ensure totally isolated interactions with APIs, and the built-in fixtures in Playwright to make setting up and tearing down so much easier, all contribute toward making the tests more consistent, maintainable, and scalable.
There is a concept of reusing fixture in which redundancy is simply removed thereby making tests run fast. Basically, Playwright is an adaptable tool and its fixture system makes it able to provide a strong solution for the purposes of simplification in API testing as well as enhancing the test framework.


