Last Updated On
Playwright can be used to get access to the REST API of the application.
In this tutorial, we will see how to handle Query Parameters in Playwright API Tests.
Table of Contents
- What is Query Parameters?
- Setup Your Playwright Testing Environment
- Update playwright.config.ts
- Writing the API Test
- Execute the tests through Test Explorer View
- Execute the tests through Command Line
- Evaluate Test Results
What is Query Parameters?
Query parameters are a way to pass information to an API flexibly and simply. They are added to the end of the API endpoint URL as a series of key-value pairs. To append query params to the end of a URL, a ‘?’ Is added followed immediately by a query parameter.
Handling HTTP query parameters in Playwright typically involves setting up your request with the desired parameters before navigating to a URL. Playwright provides methods to easily construct and use URLs with query parameters.
Below is an example of Query Parameter.
https://jsonplaceholder.typicode.com/comments?users=2
Here’s how you can handle them in Playwright:
1. Setup Your Playwright Testing Environment:
Verify that the Playwright installed in your project. If you haven’t yet installed it, you can use:
npm install playwright
2. Update playwright.config.ts
Playwright Test comes with a few built-in reporters for different needs and ability to provide custom reporters. We will add detail in playwright.config.ts to generate the html report, once the test execution is finished.
import { defineConfig } from '@playwright/test';
export default defineConfig({
reporter: 'html',
});
3. Writing the API Test
You can construct a URL using Node.js’s `URL` API, where you append your query parameters to a base URL.
// Define a type for the expected structure of a comment
type Comment = {
postId: number;
id: number;
name: string;
email: string;
body: string;
};
import { test, expect } from '@playwright/test';
test('API Testing - Query Params with Playwright', async ({ request }) => {
const queryParams = new URLSearchParams({ postId: '1' });
// Perform a GET request
const response = await request.get(`https://jsonplaceholder.typicode.com/comments?${queryParams.toString()}`);
// Check the response status code
expect(response.status()).toBe(200);
// Parse the response data
const responseBody = await response.json();
console.log(responseBody);
// Assertions based on expected response
const postIds = responseBody.map((item: Comment) => item.postId);
console.log(postIds);
// Assert that every postId in the response is '1'
expect([...new Set(postIds)]).toEqual([1]);
// Extract IDs from the response body
const ids = responseBody.map((item: Comment) => item.id);
console.log(ids);
// Expected IDs to assert against
const expectedIds = [1, 2, 3, 4, 5];
// Assert that the IDs are as expected
expect(ids).toEqual(expectedIds);
});
Explanation:
1. Type Definition
A TypeScript type Comment is defined to specify the structure of the expected response object. This includes properties like postId, id, name, email, and body.
type Comment = {
postId: number;
id: number;
name: string;
email: string;
body: string;
};
2. Imports
This line imports the test and expect functions from Playwright’s testing library. These functions provide a structure for writing tests and asserting conditions within them.
import { test, expect } from '@playwright/test';
3. Test Definition
This defines an asynchronous test case named “Query Params with Playwright”. The test receives a `request` object as a parameter, which is used to perform HTTP requests.
test('API Testing - Query Params with Playwright', async ({ request })
4. Query Parameters Setup
The `URLSearchParams` API is utilized to build the query parameters, in this case, `postId=1`.
These query parameters are appended to the base URL to form the complete URL for the GET request.
const queryParams = new URLSearchParams({ postId: '1' });
5. Performing a GET Request
Sends a GET request to the specified URL.
const response = await request.get(`https://jsonplaceholder.typicode.com/comments?${queryParams.toString()}`);
6. Checking the Response Status Code
Retrieve HTTP status code for response validation.
expect(response.status()).toBe(200);
7. Parsing the Response Data
Parse response data into JSON format
const responseBody = await response.json();
8. Logging the Response
This outputs the response body to the console, allowing you to see the returned JSON data.
console.log(responseBody);
9. Perform assertions on the response
The assertions verify that the response contains expected data.
- The code extracts and logs postIds from each item in the `responseBody`.
- An assertion ensures all postId‘s in the response are 1, corresponding to the query parameter used
- Similarly, ids are extracted, logged, and compared against a predefined list of expected IDs [1, 2, 3, 4, 5].
- An assertion checks that the `ids` match the expected IDs. This ensures that the response is consistent with the anticipated results when querying with postId=1
// Assertions based on expected response
const postIds = responseBody.map((item: Comment) => item.postId);
console.log(postIds);
// Assert that every postId in the response is '1'
expect([...new Set(postIds)]).toEqual([1]);
// Extract IDs from the response body
const ids = responseBody.map((item: Comment) => item.id);
console.log(ids);
// Expected IDs to assert against
const expectedIds = [1, 2, 3, 4, 5];
// Assert that the IDs are as expected
expect(ids).toEqual(expectedIds);
4. Execute the tests through Test Explorer View
Go to the funnel shape icon called “Testing” or “Test Explorer View”. You can run the tests from the test Explorer view too now. You can run all of the tests in all of the test specs in this directory.
You can also come in and run all of the tests in a particular specification file. Alternatively, run individual tests within a specification file. Here, I want to run the tests of api_queryparam_tests.spec.ts file.

The output of the above program is

5. Execute the tests through Command Line
You can also run the tests through the command line. Go to the terminal and use the below command:-
npx playwright test api_queryparam_tests.spec.ts
This command runs all the tests present in this file.

6. Evaluate Test Results
Analyze console outputs and assertions to validate the response data, ensuring that your API endpoints are functioning as designed.
Playwright generates a test report after the execution of the tests. This test report can be viewed by using the below command:
npx playwright show-report
The output of the above command is

Below is an example of Index.html Report generated by Playwright.



To know more about Playwright UI mode, please refer to this website – https://playwright.dev/docs.