Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

How to Get JSON Responses with Puppeteer and Playwright

Wait for the right browser response before triggering an action, check its status, and parse the body with response.json().

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To read JSON returned by a browser action, register a waitForResponse before clicking or otherwise triggering the request, await the matching response, check its HTTP status, and then call await response.json(). Use Puppeteer or Playwright’s page-response API for traffic initiated by the page; use Playwright’s APIRequestContext when you want to make a direct API call instead.

Get a JSON response after a page action

The wait must be set up before the action. This prevents a fast response from arriving before your code starts listening. Match the endpoint closely enough to distinguish it from other requests the page may make.

As an Amazon Associate I earn from qualifying purchases.

Puppeteer

const responsePromise = page.waitForResponse(response =>
  response.url().includes('/api/items') &&
  response.status() === 200
);

await page.click('button#load-items');
const response = await responsePromise;
const data = await response.json();

console.log(data);

page.waitForResponse accepts a URL or predicate and resolves with the matching HTTPResponse. The response’s json() method parses its body and throws if the body is not valid JSON. Check status() or ok() separately from parsing. See the Puppeteer Page.waitForResponse reference and HTTPResponse reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Playwright

const responsePromise = page.waitForResponse(response =>
  response.url().includes('/api/items') &&
  response.status() === 200 &&
  response.request().method() === 'GET'
);

await page.getByRole('button', { name: 'Load items' }).click();
const response = await responsePromise;
const data = await response.json();

console.log(data);

Playwright’s matcher can be a URL string, regular expression, or predicate. Including the request method and expected status can help isolate the intended response. The official Page.waitForResponse documentation demonstrates creating the wait before clicking.

Check status and parse errors independently

A response can arrive with an unsuccessful HTTP status, and a successful status does not guarantee that its body is valid JSON. Treat those as separate checks. For example, if you want to report non-2xx responses instead of letting an unexpected body confuse the diagnosis:

const response = await responsePromise;

if (!response.ok()) {
  throw new Error(`HTTP ${response.status()}: ${response.url()}`);
}

let data;
try {
  data = await response.json();
} catch (error) {
  throw new Error(`Response was not valid JSON: ${error.message}`);
}

When parsing fails, inspect the response text and headers to determine whether the server returned HTML, an empty body, or another format. Puppeteer documents that HTTPResponse.json() throws when JSON.parse cannot parse the body; Playwright’s page Response also provides body-reading methods. See the Playwright Response reference.

Make a direct request with Playwright

If no browser action is needed and the goal is simply to call an endpoint, use Playwright’s APIRequestContext. This is a different workflow from observing a page’s network traffic: the returned object is an APIResponse, not the page’s Response.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const response = await request.get('/api/items');

if (!response.ok()) {
  throw new Error(`HTTP ${response.status()}`);
}

const data = await response.json();
console.log(data);

APIResponse also provides body(), text(), status(), and ok(). Its body remains in memory until the request context closes; in a long-running workflow, dispose of responses after use when you want to release their bodies sooner. Consult the Playwright APIResponse documentation.

Choose the right way to observe traffic

  • One interaction, one response: use waitForResponse with a URL or predicate. It keeps the request tied to the action that caused it.
  • Ongoing or broad monitoring: use Playwright’s page.on('response', handler) event. It receives responses as status and headers arrive; you can then decide which ones to inspect.
  • Direct API access: use Playwright APIRequestContext rather than triggering page UI solely to reach an endpoint.
  • Request control or mocking: interception is an option when you need to modify, abort, or fulfill requests, but it is not needed for passive response reading.

Troubleshoot missing or unusable JSON

The wait never resolves

Confirm the click actually triggers the request and that the URL predicate matches the final request URL. A page may call a different endpoint, use a different method, or make several similar requests. Start with a stable path and add method or status conditions only when they match the real traffic.

The wrong response is captured

Narrow the predicate using endpoint path, request method, and, where appropriate, status. Avoid matching only a broad string such as /api on a busy page.

The response has an error status

A 404 or 503 is still an HTTP response; inspect its status and body rather than treating it as a transport failure. Playwright distinguishes an HTTP response from a request that fails before an HTTP response can be received, such as a network error. For the latter, inspect request-failure handling and network conditions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

response.json() throws

The body may be HTML (for example, an error page), empty, or a different format. Read response.text() where available and inspect headers before assuming the endpoint returned JSON. A successful parse alone does not prove the HTTP request succeeded.

Considering request interception

Interception changes network flow and places responsibility on your handlers to resolve requests. The Puppeteer project’s official Request Interception guide states: “Once request interception is enabled, every request will stall unless it’s continued, responded or aborted.” Do not enable it just to read a response body; reserve it for cases such as stubbing or controlling requests.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If the job is to capture a page image or PDF rather than inspect its JSON network response, ScreenshotNeo offers a one-request screenshot API. It accepts a URL and returns a clean PNG, JPEG, WebP, or PDF; it is not a replacement for parsing an API response.

curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://stripe.com 
  -o shot.webp

See the ScreenshotNeo API documentation for request options. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each cleanup step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. ScreenshotNeo also has an MCP server with tools for AI agents to take screenshots, get page information, and capture PDFs. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month with no card.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.