NashTech Blog

Playwright API Testing: Detailed guide with examples

Picture of Huyen Le
Huyen Le
Table of Contents

API testing plays a crucial role in modern software quality assurance. It helps QA teams validate backend functionality early, faster, and more reliably than UI testing alone. While Playwright is widely known for browser automation, it also provides powerful and easy-to-use support for API testing, making it an excellent choice for QA engineers who want to test both UI and API within a single framework.

This guide will help you get started with API testing in Playwright, especially if you are a manual tester transitioning into automation.

1. Playwright API Testing Overview

Playwright provides a robust framework for automating end-to-end (E2E) testing, including powerful capabilities for API testing. By understanding how Playwright interacts with APIs, developers can create efficient, reliable automation scripts that handle complex workflows and performing integration testing with backend systems.

How to Use Playwright for API Testing?

Playwright uses a simple yet effective approach to handle API testing by making HTTP(S) requests, enabling interaction with web services in the same way a browser interacts with a website. Here’s how you can leverage Playwright for API testing:

  • DELETE Request: Removes a resource. Playwright’s request.delete() allows you to remove data from the server and is used to delete records or entities from the system.
  • POST Request: Used to create new resources. Playwright’s request.post() allows you to send data to the server to create new entities. POST requests are essential for creating bookings or initiating processes.
  • GET Request: Retrieves existing resources. Playwright’s request.get() helps to fetch and validate the data returned by the server. GET requests are ideal for verifying returned data, such as fetching booking details.
  • PUT Request: Updates existing resources. Use Playwright’s request.put() to modify resource details, such as updating user or booking information. PUT requests fully replace a resource with new data.
  • PATCH Request: Partially updates a resource. Playwright’s request.patch() is ideal for modifying certain attributes without overwriting the entire entity.

How to Handle Dynamic Data in Playwright API Testing?

  • In Playwright, dynamic data handling can be managed with faker-js for generating test data or luxon for managing dates. This enables realistic, flexible API testing without hardcoded values.

Best Practices for Playwright API Testing

  • Assertions: Always validate the response status and data to ensure expected behavior.
  • Error Handling: Test failures and edge cases to confirm proper API behavior under error conditions.
  • Environment Configuration: Use Playwright config to manage base URLs and environments.
  • Clean Data: Delete any created test resources to maintain a clean environment for future runs.

By integrating API testing directly into Playwright, QC can create comprehensive end-to-end tests that ensure both front-end and back-end components of an application work together seamlessly.

2. Why use Playwright for API Testing?

  • Playwright is useful for testing the user interface of applications that rely on APIs, such as single-page applications (SPAs) or progressive web apps (PWAs) that use APIs to fetch data or perform other operations in the background.
  • In Playwright API testing, we will use APIRequestContext class, which sends all kinds of HTTP(S) requests over the network. APIRequest class is used for creating APIRequestContext instances. API Request’s instance can be created by Playwright’s request.
  • QA teams can test developed software in different browser versions, and operating systems, as well as emulate a real device such as a mobile phone or tablet to make sure it provides consistent behavior across diverse user test environments and works as expected.
  • Playwright is really fast and flexible and might be tailored to specific requirements of many testing projects.
  • The learning curve of Playwright is fast. QA teams can start write tests in JavaScript with ease reducing the time required for test automation coverage.

3. Setup Playwright for API Testing

Before we look into the actual implementation of Playwright API testing with examples, let’s quickly set up the Playwright. Further, you can use it to create a working example code.

  • Step 1

To start with, you need to have Node.js installed on your machine. You can download it directly from the Node.js website and install it on your machine if you are not already using it. Once installed, check the version:

node -v
Playwright API Testing node -v
  • Step 2

Download and Install Visual Studio Code.

  • Step 3

Open your integrated terminal and run the following command.

mkdir playwright-api-testing
  • Step 4

Open the directory.

cd playwright-api-testing
  • Step 5

You can install Playwright using npm or yarn, and another way is by VS Code Extension.

In this Playwright API testing tutorial, we will install the Playwright using the npm command.

On your terminal, type:

npm init playwright@latest
Playwright API Testing npm init playwright@latest
Playwright API Testing npm init playwright@latest
  • Step 6

Let’s install a few other packages we will use, like faker-js to generate test data, luxon to generate date, and rimraf to clean up the folder before each test run.

npm install --save-dev @faker-js/faker luxon rimraf
Playwright API Testing npm install --save-dev @faker-js/faker luxon rimraf

Once the installation of packages is complete, a folder node_module will be created with all the dependencies.

  • Step 7

By default .gitignore file will be created so that unwanted files are not committed to the code repository.

node_modules/
/test-results/
/playwright-report/
/playwright/.cache/
gitignore

4. Playwright API Testing Example

Let’s take a deep dive into Playwright API testing capabilities by creating a sample project to test the Restful-booker API. This site contains a list of API endpoints developed to test the different API operations like POST, GET, PUT, PATCH, and DELETE with status codes and responses, and it acts as a playground..

API Testing Approach
For easy understanding, we will create a simple Playwright API testing approach:
POST – We will look into three different ways to do a POST call.
– Create a booking by providing static data.
– Create a booking by providing data from the JSON file.
– Create a booking by creating data at run time that looks realistic and unique. To achieve this, we will use the faker-js npm package, which will give you test data.

Response Validation – Assert the response by either comparing it with JSON data or matching it with data stored in the variable.
GET – Get the booking details by using some of the techniques of query param, without query param and path param. And assert the response for each type.
PUT – Update booking attributes for an existing resource and assert the response.
PATCH – Partially update an existing resource (not all attributes required) and assert the response.
DELETE – Finally, we will delete the booking and assert the response code.

Clone the Playwright API testing GitHub repository below to follow the steps mentioned in this Playwright API testing tutorial.

LambdaTest


Then let’s take a deep dive into the Playwright API testing example in the below sections

Configuration

With little changes in the playwright.config.js file, you can start creating API tests.

  • Step 1:

Update baseURL in the playwright.config.js file so you can use it in each endpoint testing without specifying them.
baseURL: ‘https://restful-booker.herokuapp.com

  • Step 2

Keeping one browser enabled, you can disable all other browsers in the configuration file.
Playwright API Testing configuration file

POST Example

Below are three different ways to pass the data in the body while making a POST request. Let’s dive deep into it in this Playwright API testing tutorial section.

POST – Booking with static data

Sends HTTP(s) POST request and returns its response. In this Playwright API testing tutorial section, you will see how a POST call can be made by passing the static data in the bod

Implementation
To create a new booking, we will send a POST request to the /booking endpoint, and you need to provide the request body or payload in the request. Print the JSON response in the console to ensure you have received the entire response. As the endpoint will return a status code of 200 and ok as a status message, you should confirm this using an expect condition.
Also, you can verify if the response body has certain data:
firstname
lastname
totalprice
depositpaid

Code Walkthrough
In this test, we have made a POST call to an endpoint /booking. Since it’s a POST request, we must specify the body mentioned in the data.

/booking

Once the request is completed, we will receive the response. We assert by using expect condition for the ok message and status code 200.

Playwright API Testing expect condition

Also, we assert the response body to check the key and value. First, we store the JSON response data in a constant, then verify the firstname, lastname,totalprice, and depositpaid.

Playwright API Testing response body

Execution
Run the following command:

npx playwright test tests/01_post_static_data.spec.js
Playwright API Testing npx playwright test tests/01_post_static_data.spec.js

When we execute the request, it prints the response body as we have used console.log, then it asserts and marks the test as passed.
HTML Report
To get the HTML report, you can run the command:

npx playwright show-report
Playwright API Testing npx playwright show-report

POST – Booking with static data specified in JSON file

In this section of the Playwright API testing tutorial, we will see how a POST call can be made by passing the static data in the body, which is mentioned in the JSON file.
Create a folder with the name test-data and then add a JSON file with the name booking-details.json. In the booking-details file, mention all the booking details you must pass while making a POST call.

Implementation
To create a new booking by passing the data from JSON in POST request to the /booking endpoint, we need to provide the request body by using a JSON file. The rest of the implementation of the code would be the same as mentioned in the previous approach.

Code Walkthrough
In this test, we made a POST call to an endpoint /booking. Since it’s a POST request, we must specify the body mentioned in the data. However, we specify this data in the JSON file and then call this JSON data in the test. To achieve this, we first import the JSON data, store it in constant, and then call this in the test under data.

Playwright API Testing POST call to an endpoint /booking

Once the request is completed, we will receive the response. We assert by using expect condition for the ok message and status code 200.

Playwright API Testing status code 200

Also, we assert the response body to check the key and value.

response-body

Execution
Run the following command:

npx playwright test tests/02_post_static_json_data.spec.js
Playwright API Testing npx playwright test tests/02_post_static_json_data.spec.js

When we execute the request, it prints the response body as we have used console.log, then it does the assertions and marks the test as passed. It is the same as the previous one, but we have only optimized the test to use data from a JSON file.
HTML Report
To get the HTML report, you can run the command:

npx playwright show-report
Playwright API Testing npx playwright show-report

POST – Booking with dynamic data

In this Playwright API testing tutorial section, we will see how a POST call can be made by passing the dynamically generated data in the body.
You must import faker-js to create random test data and luxon to generate dates. Store the value in const and use it to build the JSON body.

Implementation
To create a new booking by passing the dynamically generated data in the body by faker-js and luxon library in the POST request to the /booking endpoint. The rest of the implementation of the code would be the same as mentioned in the previous approach.

Code Walkthrough
In this test, we made a POST call to an endpoint /booking. Since it’s a POST request, we must specify the body mentioned in the data. However, we dynamically generate this data at the run time by using faker-js and luxon npm packages so that it will send a new set of data every time we request.

Playwright API Testing faker-js and luxon npm packages

Once the request is completed, we will receive the response. We assert by using expect condition for the ok message and status code 200.

Playwright API Testing status code 200

Also, we assert the response body to check the key and value.

Playwright API Testing response body to check the key and value

Execution
Run the following command:

npx playwright test tests/03_post_dynamic_data.spec.js
Playwright API Testing npx playwright test tests/03_post_dynamic_data.spec.js

When we execute the request, it prints the response body as we have used console.log, and then it asserts and marks the test as passed. It is the same as the previous one, but here, we have only optimized the test to use data from a faker-js library and will always generate a new data set.
HTML Report
To get the HTML report, you can run the command:

npx playwright show-report
Playwright API Testing npx playwright show-report

GET Example

Below are four different ways to make a GET request. Let’s look into this in detail in this section of this Playwright API testing tutorial.

GET all bookings IDs

Here, we will see how a GET call can be made to return the ids of all the bookings within the API.

Implementation
To get all bookings, we will use a GET request to the /booking endpoint and need not provide the request body or payload in this request.
You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you must verify it with the expect condition.

Code Walkthrough
In this test, we made a GET call to an endpoint /booking. Since it’s a GET request, we don’t need to specify the body and skip using data, and here we will get all the booking details.

Once the request is completed, we will receive the response. Here, we assert by using expect condition for the ok message and status code 200.

Playwright API Testing status code 200

Execution
Run the following command:

npx playwright test tests/04_get_all_booking_details.spec.js
Playwright API Testing npx playwright test tests/04_get_all_booking_details.spec.js

When you execute the request, it prints the response body as we have used console.log, and then it asserts and marks the test as passed.
HTML Report

marks-the-test-as-passed

GET specific booking IDs

In this Playwright API testing tutorial section, we will see how a GET call can be made to return a specific booking based on the booking ID provided.

Implementation
To get a specific booking, we will use a GET request to the /booking/:id endpoint, and we don’t need to provide the request body or payload in this request. You can print the complete JSON response in the console just to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you must verify it with the expect condition.

Code Walkthrough
In this test, we made a GET call to an endpoint /booking/1. Since it’s a GET request, we don’t need to specify the body and skip using data, and here we will get only one booking detail.

here-we-will-get-only-one-booking-detail

Once the request is completed, we receive the response. Here, we assert by using expect condition for the ok message and status code 200.

expect-condition-for-the-ok-message-and-status-code

Execution
Run the following command:

npx playwright test tests/05_get_specific_booking_details.spec.js
05_get_specific_booking_details

When you execute the request, it prints the response body as we have used console.log, and then it asserts and marks the test as passed.
HTML Report
To get the HTML report, you can run the command:

npx playwright show-report

get-the-html-report-command

GET bookings by applying Filter example 1

In this section of this Playwright API testing tutorial, we will see how a GET call can be made to optionally add query strings to search and return a subset of booking IDs based on the filter string provided.
Implementation
To get the subset of booking, we will use a GET request to the /booking endpoint, and we don’t need to provide the request body or payload in this request.
You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you need to verify it with the expect condition.

Code Walkthrough
In this test, we made a GET call to an endpoint /booking. Since it’s a GET request, we need not specify the body and skip using data. Here, we apply a filter on the data by using parameters in params, and it returns all the matching booking details.

filter-on-the-data-by-using-parameters

Once the request is completed, we will receive the response. Here, we assert by using expect condition for the ok message and status code 200.

we-assert-by-using-expect-condition-for-the-ok-message

Execution
Run the following command:

npx playwright test tests/06_get_booking_details_query_param.spec.js

06_get_booking_details_query_param

When you execute the request, it prints the response body as we have used console.log, and then it asserts and marks the test as passed.
HTML Report
To get the HTML report, you can run the command:

npx playwright show-report

npx playwright show-report

GET bookings by applying Filter example 2

In this Playwright API testing tutorial section, we will see how a GET call can be made. This is another example where we can optionally add query strings to search and return a subset of booking IDs based on the filter string provided
Implementation
To get the subset of bookings, we will use a GET request to the /booking endpoint, and we don’t need to provide the request body or payload in this request.
You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and an ok as a status message, you need to verify it with the expect condition.

Code Walkthrough
This is another test where we make a GET call to an endpoint /booking. Since it’s a GET request, we don’t need to specify the body and skip using data. Here, we apply a filter of check-in and check-out dates by using parameters in params, and it returns all the matching booking details.

make-a-get-call-to-an-endpoint

Once the request is completed, we will receive the response. Here, we assert by using expect condition for the ok message and status code 200.

we-will-receive-the-response

Execution
Run the following command:

npx playwright test tests/07_get_booking_details_query_param.spec.js

07_get_booking_details_query_param

When you execute the request, it prints the response body as we have used console.log and asserts and marks the test as passed.
HTML Report
To get the HTML report, you can run the command:

npx playwright show-report

npx-playwright-report

PUT – Updating a resource

It is used to update the current booking details. In this section of the Playwright API testing tutorial, we need to specify a fully updated body.

Implementation
To update the current booking details, we will use a PUT request to the /booking/1 endpoint, and we need to provide the request body or payload in the request, which needs to be updated.
You can print the complete JSON response in the console to check what we receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you need to verify it with the expect condition.

Code Walkthrough
In this test, we make a POST call to an endpoint /auth to generate the token, which needs to be passed with the PUT request. The username and password need to be specified in the body mentioned in the data.

post-call-to-an-endpoint

Once the request is completed, we receive the response. Here, we store the token in a variable.

store-the-token-in-a-variable

Now we make a PUT call to an endpoint /booking/1 and pass the token in the header and body in the data.

put-call-to-an-endpoint

We will receive the response and need to make an assert by using expect condition for the ok message and status code 200.

response-and-need-to-make-an-assert

Also, we will assert the response body to check the key and value.

we-will-assert-the-response-body-to-check

Execution
Run the following command:

npx playwright test tests/08_update_booking_details.spec.js

08_update_booking_details

When you execute the request, it prints the response body as we have used console.log, a newly generated token, and then it prints another response in the console, which is for the PUT request, and then it asserts and marks the test as passed.
HTML Report
To get the HTML report, you can run the command:

npx playwright show-report

you-can-run

PATCH – Updating a resource partially

In this Playwright API testing tutorial section, we will see how to use PATCH to update the current booking with a partial payload.

Implementation
To update the booking with the partial payload, we will use a PATCH request to the /booking/1 endpoint, and we need to provide the partial request body or payload, which needs to be updated. You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, we need to verify it with the expect condition.

Code Walkthrough
In this test, we make a POST call to an endpoint /auth to generate the token, which needs to be passed with the PATCH request. The username and password need to be specified in the body, which is mentioned in the data.

passed-with-the-patch-request

Once the request is completed, we will receive the response. Here, we will store the token in a variable.

here-we-will-store-the-token

Now we will make a PATCH call to an endpoint /booking/1 and pass the token in the header and body in the data.

token-in-header

We will receive the response and assert by making use of expect condition for the ok message and status code 200.

we-will-receive-the-response-and-assert-by-making-use-of-expect

Also, we will assert the response body to check the key and value.

check-key-value

Execution
Run the following command:

npx playwright test tests/09_partial_update_booking_details.spec.js

09_partial_update_booking_details

When you execute the request, it prints the response body as we have used console.log, a newly generated token, and then it prints another response in the console, which is for the PATCH request, and then it asserts and marks the test as passed.
HTML Report
To get the HTML report, you can run the command:

npx playwright show-report

Playwright API Testing npx playwright show-report09

DELETE Example

It is used to delete the resource. In this section of the Playwright API testing tutorial, we will delete the booking details.

Implementation
To delete a booking, we will use the DELETE request to the /booking/1 endpoint, and we don’t need to provide the request body or payload in this request.
You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you need to verify it with the expect condition.

Code Walkthrough
In this test, we make a POST call to an endpoint /auth to generate the token, which needs to be passed with the DELETE request. The username and password need to be specified in the body, which is mentioned in the data.

need-specified

Once the request is completed, we will receive the response. Here, we will store the token in a variable.

store

Now we will make a DELETE call to an endpoint /booking/1 and pass the token in the header, and the body is not required.

will-make-a-delete-call

We will receive the response and assert by using expect condition for Created message and status code 201.

created-message-and-status-code

Execution
Run the following command:

npx playwright test tests/10_delete_booking_details.spec.js

10_delete_booking_details

When you execute the request, it prints the response body as we have used console.log and then asserts and marks the test as passed.
HTML Report
To get the HTML report, you can run the command:

npx playwright show-report

npx-playwright-show-repo

5. Best Practices for API Testing with Playwright

A poor-quality API testing can significantly impact the bottom line of your future software products. Here’s what you should consider when rolling out API testing with Playwright.

#1: Properly Organize Test Cases

Effective organization of test cases is fundamental to successful software testing. That’s why making proper test organization is crucial. So,

You should categorize your test cases into logical groups or test suites based on the features or functional areas of your application. In case of API testing – collections.

In addition to that, you need to give clear and descriptive names to each test case. Don’t forget that the name should convey the test’s purpose and the scenario it covers in order to simplify understanding and maintenance.

Also, you should establish a clear priority for your test cases. Make sure that the critical tests can be identified and run first. This prioritization helps focus on the most essential scenarios.

Furthermore, you can implement tagging to further categorize test cases. For example, “regression,” “performance,” or “security” provide valuable metadata for test case management.

#2: Parameterize Test Data

By parameterizing test datasets, you enhance the coverage and comprehensiveness of your API testing. This practice is invaluable for verifying the stability and reliability of your APIs under various conditions and inputs, ultimately leading to better software quality. Once you identify the different variations of test data that your API test cases need to cover, you need to consider scenarios with various inputs.

Then you should organize test datasets into data sets that represent a distinct combination of input values and expected outcomes for a specific test case. Don’t forget to capture and record the results of each test iteration to make appropriate changes.

#3: Handle Errors Effectively

Effective error handling is crucial for ensuring the reliability and robustness of your APIs. It helps identify issues that users might encounter in real-world scenarios and allows you to immediately address these issues before they impact your application’s users. That’s why you should make error scenarios granular. For instance, invalid data formats, missing parameters, insufficient permissions, and overloads on a server directly. This helps you provide robust error handling and mitigate potential vulnerabilities.

#4: Monitor and alert

When implementing monitoring and alerting, you can detect and respond to errors in real time. Once alerts for specific error conditions are set up, issues can be addressed promptly. What’s more, you can craft error messages that are user-friendly and informative. This will guide users on how to resolve the issues.

#5: Maintain Your Test Suite Regularly

As your application evolves, your API endpoints and data formats may change. That’s why you should regularly update your tests to check these changes and ensure they remain accurate. If your tests rely on specific test datasets, keep the data sets up-to-date to verify that the test data reflects the most recent data used in your application. What’s more, you can focus on incorporating data cleanup to remove test datasets generated during test runs. This helps you eliminate potential test failures due to data conflicts.

6. Conclusion

Playwright is a powerful tool for automating web application testing and can also be used for API testing. Playwright provides a simple and easy-to-use API that allows you to make HTTP requests, perform assertions, and parse responses. By now, you have a fair understanding of Playwright requests, and how Playwright API testing can be done with working examples for POST, GET, PUT, PATCH, and DELETE requests.


Picture of Huyen Le

Huyen Le

I am a Senior Test Engineer at NashTech Vietnam, with years of experience in software testing. I focus on ensuring software quality and reliability, while sharing insights and best practices to help others improve their testing processes.

Leave a Comment

Suggested Article

Discover more from NashTech Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading