SlideShare a Scribd company logo
4
Most read
5
Most read
16
Most read
Leveraging Playwright for API Testing.pdf
Leveraging Playwright for API Testing
API helps to build the core of any application in the modern software
architecture. They facilitate communication between different systems
and services over the network. Due to their utmost importance, it
becomes very important to ensure that they work as expected and
efficiently handle the different scenarios without breaking.
API Testing is about sending requests to the endpoints and asserting
that the responses are as expected. Different test cases are executed
on the API’s to validate success and error conditions, edge cases,
integration between multiple API’s, performance and security.
To ensure speed, reliability and proper coverage, automation of APIs
can be the right approach to test APIs.
API Basics – CRUD Operations
In API, CRUD functions serve as the basis of any software application.
And testing these operations, viz, Create, Read, Update and
Delete(CRUD) is an essential part of any automation testing
framework. Let us look at what these CRUD operations are-
Create Operations
As can be understood from the name, Create operations are used to
create a resource on the server. Some of the important checkpoints
for create operations are listed below-
● Use the POST or PUT methods to add entities.
● Parameterize values like IDs, names, status codes to validate
different combinations.
● Put assertions to check the response data
● Test various input combinations and boundary values
Read Operations
The Read operations help extract existing data from the server using
the GET Method. Few checkpoints for using the Read Operations are-
● Using pagination and filters to check response
● Validate fields present in response
● Validate for null and invalid parameters
● Assert if response structure matches API documentation
Update Operations
Updates can be made to server resources by using the PATCH or
PUT Methods. Some basic checkpoints to look out for while
performing Update Operations are listed below-
● Sending the updated fields via JSON body
● Validate that the updates are reflected in the response body
● Validation of the status code and response message
● Verification by making the mandatory fields null
● Parameterization to reuse scripts
● Update nested APIs to check logical updates
Delete Operations
Resources can be removed from the server using the DELETE
method. A few points to check while performing the Delete Operations
are listed below-
● Assert response status code 404 or 401 Not Found after
Deletion
● Attempt to delete invalid IDs
● Restoring of deleted entries to reset state
● Parameterization of IDs to be deleted to make reusable scripts
If you ensure that you are covering all the CRUD Operations with the
elaborate test cases, a strong foundation of your application will be
set. Add to it the advantages you would yield with the automation
framework enhancing the test coverage and reusability of the tests.
Benefits of Using Playwright for API Testing
While Playwright is commonly used for browser automation and UI
testing, its capabilities also make it well-suited for testing web APIs.
Some of the advantages are –
● Simplicity and Familiarity of Syntax: Playwright will allow you to
use the same DOM-centric commands(as used in browser
automation) for API Testing.
● Built-in Assertions: You can use assertions to validate the
response status, header, body or the structure.
● You can easily integrate UI and API tests in a single framework.
● Playwright stores and handles cookies and credentials, thereby
maintaining state of execution.
● It supports authentication mechanisms like the basic auth or the
bearer tokens.
● You may use test hooks to mock some API behaviour.
● You can easily scale the existing framework to accommodate
more tests.
● You can easily scale the existing framework to accommodate
more tests.
Prerequisites to Write Playwright API Tests
To start writing the API automation tests using Playwright you need to
ensure that the below mentioned things are installed in your systems-
● Node.js and NPM installed to run playwright
● A code editor like VS Code
● API Documentation
● Some other packages like faker-js, rimraf, etc. These packages
will support your framework by helping you generate test
data(faker-js) and clean up folders(rimraf) before new executions
Let us now jump on to writing our first API test using Playwright.
Writing Playwright API Tests
We will now practically write and execute Playwright API Tests and
refer to dummy APIs of Bookstore. The documentation has multiple
APIs that perform the different CRUD Operations. We will cover
different scenarios starting with POST/PUT methods to:
1. Create a new user using the Register User API.
2. Generate the user token using the Generate Token API.
After the registration and login is done using the Create Operations,
we will use the GET method to:
3. Get the list of available books using the Get Books API.
Set Up
1. We will first create a directory for our Playwright API Test. Open
command prompt and navigate to the folder where you would
want to house your API Test framework. Now, enter the below
command to create a directory:
mkdir playwright_api_test
You will notice in your system that a directory/folder is created:
2. Now open VS Code and then open the project/directory that you
created in Step#1.
3. In the terminal of VS Code enter the below command to install
playwright:
npm init playwright@latest
4. We will now install the helper packages, viz faker-js and rimraf
using below command:
npm install --save-dev @faker-js/faker rimraf
Once the installation of the packages is done, you will notice that
node_modules will be added to project structure with the
dependencies fetched from the packages added to it.
Once the setup is done, we will begin writing our tests. The first step is
to make changes to the configuration file. We will comment out all the
browsers except one and also add our base url to the config file, so
that we simply use the endpoint in our API calls. After the required
updates, the config file should look like below:
// @ts-check
const { defineConfig, devices } = require('@playwright/test');
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();
/**
* @see https://playwright.dev/docs/test-configuration
*/
module.exports = defineConfig({
testDir: './tests',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source
code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See
https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'https://bookstore.toolsqa.com',
/* Collect trace when retrying the failed test. See
https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
/*
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
*/
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: { ...devices['Pixel 5'] },
// },
// {
// name: 'Mobile Safari',
// use: { ...devices['iPhone 12'] },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
// name: 'Google Chrome',
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },
],
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// url: 'http://127.0.0.1:3000',
// reuseExistingServer: !process.env.CI,
// },
});
Next, we start writing our first test where we will be using the POST
method to register a user. We will be sending the user data in the
request body as shown in the code below:
const{test, expect} = require('@playwright/test');
test('User registration', async({request})=> {
const response = await request.post("/Account/v1/User",{
data:{
"userName": "gk001",
"password": "gk002@Gk002"
}
});
console.log(await response.json());
});
Execute the code by running the command below-
npx playwright test tests/register_user.spec.js
Upon execution you will see that the test is executed and the test
execution results are displayed in the console:
Now, we will be using the user that we created to generate a token.
Below is code to execute the Generate Token API.
const{test, expect} = require('@playwright/test');
test('Generate Token', async({request})=> {
const response = await request.post("/Account/v1/GenerateToken",{
data:{
"userName": "gk004",
"password": "gk002@Gk002"
}
});
console.log(await response.json());
expect(response.status()).toBe(200);
const resBody = await response.json();
expect(resBody).toHaveProperty("result","User authorized
successfully.");
});
You can execute the file in a similar way as we did above, i.e., using
the below command:
npx playwright test tests/generate_token.spec.js
The execution results will be displayed as below:
Our next API will fetch the list of books that are available in the
database. It will use the GET method and code for it is written below.
const{test, expect} = require('@playwright/test');
test('Book List', async({request})=> {
const response = await request.get("/BookStore/v1/Books");
console.log(await response.json());
expect(response.status()).toBe(200);
});
Unlike the APIs used in the above two test cases, the GET API will not
have any method body, and here we simply pass the URL endpoint
const response = await request.get("/BookStore/v1/Books");
and validate for the status code to be 200.
expect(response.status()).toBe(200);
You can execute the test case using the below command:
npx playwright test tests/generate_token.spec.js
The execution will show the list of books available in the console logs:
Conclusion
Leveraging Playwright for API testing offers a powerful,
browser-based solution that ensures comprehensive validation, faster
feedback loops, and seamless integration with UI tests for robust
end-to-end automation.
Source: This article was originally published at testgrid.io.
Leveraging Playwright for API Testing.pdf

More Related Content

Similar to Leveraging Playwright for API Testing.pdf (20)

PDF
Playwright: A New Test Automation Framework for the Modern Web
Applitools
 
PPTX
Playwright Online Training | Playwright Automation Testing Hyderabad
Jayanthvisualpath
 
PDF
Why Should we use Microsoft's Playwright
Knoldus Inc.
 
PDF
Playwright Test automation frameworktest
rushcodeharish
 
PDF
Cypress-vs-Playwright-Rematch-Applitools.pdf
Applitools
 
PDF
Cypress vs Playwright: A Comparative Analysis
Shubham Joshi
 
PDF
No drama here - E2E-testing django with playwright
Mastacheata1
 
PDF
Playwright, Cypress, or TestGrid: A Feature-by-Feature Breakdown for Test Aut...
Shubham Joshi
 
PPTX
PlayWright Course Online - PlayWright Training.pptx
himavanthvisualpath
 
PPTX
UI Test Automation With Playwright with Pytest
Arshad QA
 
PDF
Playwright: An Emerging Tool in Test Automation
Anna Royzman
 
PDF
Guide to Playwright Debugging – Tips and Techniques.pdf
Steve Wortham
 
PPTX
QA or the Highway 2022.pptx
Perfecto Mobile
 
PPTX
Dev Day 2024: Jonathan Frere - Playwright: Das Beste aus dem Dramatiker herau...
emmaberlin1
 
PPTX
Browser Automation with Playwright – for integration, RPA, UI testing and mor...
Lucas Jellema
 
PDF
playwrithgttttttttttttttttttttttSlides.pdf
SarvjeetKumarSingh1
 
PDF
How to Use Playwright Locators_ A Detailed Guide.pdf
kalichargn70th171
 
PDF
playwrightmeetup-14jan2021-210114173639.pdf
ManjuBiradar6
 
PDF
Next-Level API Automation Testing Techniques – Part 2
digitaljignect
 
PPTX
ОЛЕКСІЙ ОСТАПОВ «Найкрутіші особливості автоматизації на Playwright Python» K...
QADay
 
Playwright: A New Test Automation Framework for the Modern Web
Applitools
 
Playwright Online Training | Playwright Automation Testing Hyderabad
Jayanthvisualpath
 
Why Should we use Microsoft's Playwright
Knoldus Inc.
 
Playwright Test automation frameworktest
rushcodeharish
 
Cypress-vs-Playwright-Rematch-Applitools.pdf
Applitools
 
Cypress vs Playwright: A Comparative Analysis
Shubham Joshi
 
No drama here - E2E-testing django with playwright
Mastacheata1
 
Playwright, Cypress, or TestGrid: A Feature-by-Feature Breakdown for Test Aut...
Shubham Joshi
 
PlayWright Course Online - PlayWright Training.pptx
himavanthvisualpath
 
UI Test Automation With Playwright with Pytest
Arshad QA
 
Playwright: An Emerging Tool in Test Automation
Anna Royzman
 
Guide to Playwright Debugging – Tips and Techniques.pdf
Steve Wortham
 
QA or the Highway 2022.pptx
Perfecto Mobile
 
Dev Day 2024: Jonathan Frere - Playwright: Das Beste aus dem Dramatiker herau...
emmaberlin1
 
Browser Automation with Playwright – for integration, RPA, UI testing and mor...
Lucas Jellema
 
playwrithgttttttttttttttttttttttSlides.pdf
SarvjeetKumarSingh1
 
How to Use Playwright Locators_ A Detailed Guide.pdf
kalichargn70th171
 
playwrightmeetup-14jan2021-210114173639.pdf
ManjuBiradar6
 
Next-Level API Automation Testing Techniques – Part 2
digitaljignect
 
ОЛЕКСІЙ ОСТАПОВ «Найкрутіші особливості автоматизації на Playwright Python» K...
QADay
 

More from Steve Wortham (20)

PDF
Selenium Testing The Complete Step-by-Step Tutorial.pdf
Steve Wortham
 
PDF
The SAP Testing A Comprehensive Guide.pdf
Steve Wortham
 
PDF
The Ultimate Guide to Salesforce Automation.pdf
Steve Wortham
 
PDF
Top AI Testing Tools to Streamline Your Automation Efforts.pdf
Steve Wortham
 
PDF
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
Steve Wortham
 
PDF
findElement and findElements in Selenium_ Use Cases with Examples.pdf
Steve Wortham
 
PDF
Streamlining Enterprise Demands Selecting the Ideal Cloud Test Automation.pdf
Steve Wortham
 
PDF
Geolocation Testing for Global Success_ Test from Anywhere.pdf
Steve Wortham
 
PDF
The Next Wave of Software Testing_ Trends Shaping 2025.pdf
Steve Wortham
 
PDF
Creating an Effective Enterprise Testing Strategy_ Best Practices and Conside...
Steve Wortham
 
PDF
How to Inspect Elements on Android Devices.pdf
Steve Wortham
 
PDF
GUI Testing_ Best Practices, Tools, and Checklists You Can’t Miss.pdf
Steve Wortham
 
PDF
Introducing TestGrid’s Private Device Lab.pdf
Steve Wortham
 
PDF
Scriptless Test Automation_ A Complete Guide.pdf
Steve Wortham
 
PDF
Top iOS Testing Tools and Frameworks.pdf
Steve Wortham
 
PDF
The Test Cases for E-commerce Website.pdf
Steve Wortham
 
PDF
Playwright and its Installation Guide.pdf
Steve Wortham
 
PDF
A Guide to Codeless Automation on iPhone Devices.pdf
Steve Wortham
 
PDF
Understanding DevOps, its benefits, and best practices.pdf
Steve Wortham
 
PDF
Boost Your Telecom Testing Strategy_ Steps to Achieve Seamless Connectivity.pdf
Steve Wortham
 
Selenium Testing The Complete Step-by-Step Tutorial.pdf
Steve Wortham
 
The SAP Testing A Comprehensive Guide.pdf
Steve Wortham
 
The Ultimate Guide to Salesforce Automation.pdf
Steve Wortham
 
Top AI Testing Tools to Streamline Your Automation Efforts.pdf
Steve Wortham
 
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
Steve Wortham
 
findElement and findElements in Selenium_ Use Cases with Examples.pdf
Steve Wortham
 
Streamlining Enterprise Demands Selecting the Ideal Cloud Test Automation.pdf
Steve Wortham
 
Geolocation Testing for Global Success_ Test from Anywhere.pdf
Steve Wortham
 
The Next Wave of Software Testing_ Trends Shaping 2025.pdf
Steve Wortham
 
Creating an Effective Enterprise Testing Strategy_ Best Practices and Conside...
Steve Wortham
 
How to Inspect Elements on Android Devices.pdf
Steve Wortham
 
GUI Testing_ Best Practices, Tools, and Checklists You Can’t Miss.pdf
Steve Wortham
 
Introducing TestGrid’s Private Device Lab.pdf
Steve Wortham
 
Scriptless Test Automation_ A Complete Guide.pdf
Steve Wortham
 
Top iOS Testing Tools and Frameworks.pdf
Steve Wortham
 
The Test Cases for E-commerce Website.pdf
Steve Wortham
 
Playwright and its Installation Guide.pdf
Steve Wortham
 
A Guide to Codeless Automation on iPhone Devices.pdf
Steve Wortham
 
Understanding DevOps, its benefits, and best practices.pdf
Steve Wortham
 
Boost Your Telecom Testing Strategy_ Steps to Achieve Seamless Connectivity.pdf
Steve Wortham
 
Ad

Recently uploaded (20)

PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Ad

Leveraging Playwright for API Testing.pdf

  • 2. Leveraging Playwright for API Testing API helps to build the core of any application in the modern software architecture. They facilitate communication between different systems and services over the network. Due to their utmost importance, it becomes very important to ensure that they work as expected and efficiently handle the different scenarios without breaking. API Testing is about sending requests to the endpoints and asserting that the responses are as expected. Different test cases are executed on the API’s to validate success and error conditions, edge cases, integration between multiple API’s, performance and security. To ensure speed, reliability and proper coverage, automation of APIs can be the right approach to test APIs.
  • 3. API Basics – CRUD Operations In API, CRUD functions serve as the basis of any software application. And testing these operations, viz, Create, Read, Update and Delete(CRUD) is an essential part of any automation testing framework. Let us look at what these CRUD operations are- Create Operations As can be understood from the name, Create operations are used to create a resource on the server. Some of the important checkpoints for create operations are listed below- ● Use the POST or PUT methods to add entities. ● Parameterize values like IDs, names, status codes to validate different combinations. ● Put assertions to check the response data ● Test various input combinations and boundary values Read Operations The Read operations help extract existing data from the server using the GET Method. Few checkpoints for using the Read Operations are- ● Using pagination and filters to check response ● Validate fields present in response ● Validate for null and invalid parameters ● Assert if response structure matches API documentation Update Operations Updates can be made to server resources by using the PATCH or PUT Methods. Some basic checkpoints to look out for while performing Update Operations are listed below-
  • 4. ● Sending the updated fields via JSON body ● Validate that the updates are reflected in the response body ● Validation of the status code and response message ● Verification by making the mandatory fields null ● Parameterization to reuse scripts ● Update nested APIs to check logical updates Delete Operations Resources can be removed from the server using the DELETE method. A few points to check while performing the Delete Operations are listed below- ● Assert response status code 404 or 401 Not Found after Deletion ● Attempt to delete invalid IDs ● Restoring of deleted entries to reset state ● Parameterization of IDs to be deleted to make reusable scripts If you ensure that you are covering all the CRUD Operations with the elaborate test cases, a strong foundation of your application will be set. Add to it the advantages you would yield with the automation framework enhancing the test coverage and reusability of the tests. Benefits of Using Playwright for API Testing While Playwright is commonly used for browser automation and UI testing, its capabilities also make it well-suited for testing web APIs. Some of the advantages are – ● Simplicity and Familiarity of Syntax: Playwright will allow you to use the same DOM-centric commands(as used in browser automation) for API Testing.
  • 5. ● Built-in Assertions: You can use assertions to validate the response status, header, body or the structure. ● You can easily integrate UI and API tests in a single framework. ● Playwright stores and handles cookies and credentials, thereby maintaining state of execution. ● It supports authentication mechanisms like the basic auth or the bearer tokens. ● You may use test hooks to mock some API behaviour. ● You can easily scale the existing framework to accommodate more tests. ● You can easily scale the existing framework to accommodate more tests. Prerequisites to Write Playwright API Tests To start writing the API automation tests using Playwright you need to ensure that the below mentioned things are installed in your systems- ● Node.js and NPM installed to run playwright ● A code editor like VS Code ● API Documentation ● Some other packages like faker-js, rimraf, etc. These packages will support your framework by helping you generate test data(faker-js) and clean up folders(rimraf) before new executions Let us now jump on to writing our first API test using Playwright. Writing Playwright API Tests We will now practically write and execute Playwright API Tests and refer to dummy APIs of Bookstore. The documentation has multiple APIs that perform the different CRUD Operations. We will cover different scenarios starting with POST/PUT methods to:
  • 6. 1. Create a new user using the Register User API. 2. Generate the user token using the Generate Token API. After the registration and login is done using the Create Operations, we will use the GET method to: 3. Get the list of available books using the Get Books API. Set Up 1. We will first create a directory for our Playwright API Test. Open command prompt and navigate to the folder where you would want to house your API Test framework. Now, enter the below command to create a directory: mkdir playwright_api_test You will notice in your system that a directory/folder is created: 2. Now open VS Code and then open the project/directory that you created in Step#1. 3. In the terminal of VS Code enter the below command to install playwright: npm init playwright@latest
  • 7. 4. We will now install the helper packages, viz faker-js and rimraf using below command: npm install --save-dev @faker-js/faker rimraf Once the installation of the packages is done, you will notice that node_modules will be added to project structure with the dependencies fetched from the packages added to it.
  • 8. Once the setup is done, we will begin writing our tests. The first step is to make changes to the configuration file. We will comment out all the
  • 9. browsers except one and also add our base url to the config file, so that we simply use the endpoint in our API calls. After the required updates, the config file should look like below: // @ts-check const { defineConfig, devices } = require('@playwright/test'); /** * Read environment variables from file. * https://github.com/motdotla/dotenv */ // require('dotenv').config(); /**
  • 10. * @see https://playwright.dev/docs/test-configuration */ module.exports = defineConfig({ testDir: './tests', /* Run tests in files in parallel */ fullyParallel: true, /* Fail the build on CI if you accidentally left test.only in the source code. */ forbidOnly: !!process.env.CI, /* Retry on CI only */ retries: process.env.CI ? 2 : 0, /* Opt out of parallel tests on CI. */ workers: process.env.CI ? 1 : undefined, /* Reporter to use. See https://playwright.dev/docs/test-reporters */ reporter: 'html', /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL: 'https://bookstore.toolsqa.com', /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ trace: 'on-first-retry', }, /* Configure projects for major browsers */ projects: [ { name: 'chromium',
  • 11. use: { ...devices['Desktop Chrome'] }, }, /* { name: 'firefox', use: { ...devices['Desktop Firefox'] }, }, { name: 'webkit', use: { ...devices['Desktop Safari'] }, }, */ /* Test against mobile viewports. */ // { // name: 'Mobile Chrome', // use: { ...devices['Pixel 5'] }, // }, // { // name: 'Mobile Safari', // use: { ...devices['iPhone 12'] }, // }, /* Test against branded browsers. */ // { // name: 'Microsoft Edge', // use: { ...devices['Desktop Edge'], channel: 'msedge' }, // }, // { // name: 'Google Chrome',
  • 12. // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, // }, ], /* Run your local dev server before starting the tests */ // webServer: { // command: 'npm run start', // url: 'http://127.0.0.1:3000', // reuseExistingServer: !process.env.CI, // }, }); Next, we start writing our first test where we will be using the POST method to register a user. We will be sending the user data in the request body as shown in the code below: const{test, expect} = require('@playwright/test'); test('User registration', async({request})=> { const response = await request.post("/Account/v1/User",{ data:{ "userName": "gk001", "password": "gk002@Gk002" } }); console.log(await response.json());
  • 13. }); Execute the code by running the command below- npx playwright test tests/register_user.spec.js Upon execution you will see that the test is executed and the test execution results are displayed in the console: Now, we will be using the user that we created to generate a token. Below is code to execute the Generate Token API. const{test, expect} = require('@playwright/test'); test('Generate Token', async({request})=> { const response = await request.post("/Account/v1/GenerateToken",{ data:{ "userName": "gk004", "password": "gk002@Gk002" } }); console.log(await response.json()); expect(response.status()).toBe(200);
  • 14. const resBody = await response.json(); expect(resBody).toHaveProperty("result","User authorized successfully."); }); You can execute the file in a similar way as we did above, i.e., using the below command: npx playwright test tests/generate_token.spec.js The execution results will be displayed as below: Our next API will fetch the list of books that are available in the database. It will use the GET method and code for it is written below. const{test, expect} = require('@playwright/test'); test('Book List', async({request})=> { const response = await request.get("/BookStore/v1/Books"); console.log(await response.json()); expect(response.status()).toBe(200); }); Unlike the APIs used in the above two test cases, the GET API will not have any method body, and here we simply pass the URL endpoint const response = await request.get("/BookStore/v1/Books"); and validate for the status code to be 200. expect(response.status()).toBe(200);
  • 15. You can execute the test case using the below command: npx playwright test tests/generate_token.spec.js The execution will show the list of books available in the console logs: Conclusion Leveraging Playwright for API testing offers a powerful, browser-based solution that ensures comprehensive validation, faster feedback loops, and seamless integration with UI tests for robust end-to-end automation. Source: This article was originally published at testgrid.io.