Leveraging Playwright for API Testing
API helps to build the core of any application in the modern software architecture.
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 we will 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:
Create a new user using the Register User API.
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:
- Get the list of available books using the Get Books API.
Set Up
- 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 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, ensuring 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/blog/playwright-api-testing.