Monday, May 19, 2025

How to Perform API Intercept Using Playwright

In this example we will explore how to perform api intercept in playwright. Along with the UI Automation , we can also intercept specific API Requests or Responses in our UI test . This technique will add a further validation and also help us in validating the test very quickly, In this way we can use API & UI Automation together to achieve the test execution effectively.

How to Perform API Intercept Using Playwright


Syntax to capture specific request

This example help us to capture specific request.

 // creat API response interception promise 
  const adduserapireqpromise = page.waitForRequest((request)=>{
    return request.url()==="https://thinking-tester-contact-list.herokuapp.com/users" && request.method()==="POST"
  });

  await page.locator("#submit").click();

  // wait for promise to resolve
  const adduserapireq = await adduserapireqpromise;
  const adduserapireqJson = await adduserapireq.postDataJSON();


Syntax to capture specific response

This example help us to capture specific response.

// creat API response interception promise 
    const adduserapirespromise = page.waitForResponse(response => response.url().includes("https://thinking-tester-contact-list.herokuapp.com/users"));
  
    await page.locator("#submit").click();   
  
    // wait for promise to resolve
    const adduserapires = await adduserapirespromise;
    const adduserapirescode = adduserapires.status();
    const adduserapiresjson = adduserapires.json();    

Subscribe to 'request' and 'response' events using page.on()

  • Requests: Use the page.on('request', ...) event to intercept outgoing HTTP requests.
  • Responses: Use the page.on('response', ...) event to capture server responses.

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();

  // Listen for all requests
  page.on('request', request => {
    console.log('Request:', {
      url: request.url(),
      method: request.method(),
      headers: request.headers(),
      postData: request.postData() // For POST/PUT requests
    });
  });

  // Listen for all responses
  page.on('response', response => {
    console.log('Response:', {
      url: response.url(),
      status: response.status(),
      headers: response.headers()
    });
  });

  // Navigate to a website
  await page.goto('https://example.com');

  await browser.close();
})();


Example -1 :  Capturing a Specific Request 

In the below example site , when we click on the signup button , a Post API will be triggered with Request body , now we are going to assert that API Request consists of valid email ID or not

Example Site : https://thinking-tester-contact-list.herokuapp.com/

Request payload :

How to Perform API Intercept Using Playwright

Response payload :

How to Perform API Intercept Using Playwright


// @ts-check
import { test, expect } from '@playwright/test';

test('Verify the Req body consists of valid email or not', async ({page}) => {

  //go to the side
  await page.goto("https://thinking-tester-contact-list.herokuapp.com/");
  await page.locator("#signup").click();
  await expect(page).toHaveURL("https://thinking-tester-contact-list.herokuapp.com/addUser");
  
  await page.locator("#firstName").fill("Sumit");
  await page.locator("#lastName").fill("Pradhan");
  await page.locator("#email").fill("sumit@yopmail.com");
  await page.locator("#password").fill("Demo@123");

  // creat API response interception promise 
  const adduserapireqpromise = page.waitForRequest((request)=>{
    return request.url()==="https://thinking-tester-contact-list.herokuapp.com/users" && request.method()==="POST"
  });

  await page.locator("#submit").click();

  // wait for promise to resolve
  const adduserapireq = await adduserapireqpromise;
  const adduserapireqJson = await adduserapireq.postDataJSON();
  console.log(adduserapireqJson);
  expect(adduserapireqJson.email,`expect req body to have email sumit@yopmail.com`).toBe('sumit@yopmail.com');
});

Example -2 :  Capturing a Specific Response

In the below example site , when we click on the signup button , an API will be triggered with a Response , now we are going to assert that API Response consists of valid http code or not.

test('Verify the Response status code consists of valid 201 or not', async ({page}) => {

    //go to the side
    await page.goto("https://thinking-tester-contact-list.herokuapp.com/");
    await page.locator("#signup").click();
    await expect(page).toHaveURL("https://thinking-tester-contact-list.herokuapp.com/addUser");
    
    await page.locator("#firstName").fill("Sumit");
    await page.locator("#lastName").fill("Pradhan");
    await page.locator("#email").fill("sumit"+ Math.floor(Math.random() * 1000)+"@yopmail.com");
    await page.locator("#password").fill("Demo@123");
  
    // creat API response interception promise 
    const adduserapirespromise = page.waitForResponse(response => response.url().includes("https://thinking-tester-contact-list.herokuapp.com/users"));
  
    await page.locator("#submit").click();   
  
    // wait for promise to resolve
    const adduserapires = await adduserapirespromise;
    const adduserapirescode = adduserapires.status();    
    expect(adduserapirescode,`expect res code to have 201`).toBe(201);  
  });


This is a simple example to intercept api request and response in playwright.


No comments:

Post a Comment