How do I check the response status of an API request using Playwright?


To check the response status of an API request using Playwright, you can utilize the APIResponse class. This class has a method called statusText() that returns the status text of the response. You can then use this method to determine if the response was successful or not.

Here's a TypeScript example demonstrating how to check the API response status using Playwright:

import { chromium } from '@playwright/test';

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

  // Make API request
  const apiRequest = await context.newRequest('https://ray.run/api');
  const apiResponse = await apiRequest.send();

  // Check response status
  if (apiResponse.statusText() === 'OK') {
    console.log('API request succeeded!');
    // Proceed with further actions...
  } else {
    console.error(`API request failed: ${apiResponse.statusText()}`);
    // Handle error...

  await browser.close();

In this example, we first make the API request using Playwright's APIRequestContext class and store the resulting APIResponse object in a variable. Next, we call the statusText() method on this object to get its status text. If it returns "OK", then we know that the request was successful and can proceed with further actions. If it returns anything else, then we know that there was an error and should handle it accordingly.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.