lecture 13 of 140 completed

JSON and API responses

API tests parse a response body and check its fields. response.json() is itself asynchronous.

What you'll learn

  • What JSON is and how it differs from a JavaScript object
  • Why reading a response body needs await
  • How to choose which fields of a response to check

An API test asks Shelf for a loan and checks the title. It stops with "Cannot read properties of undefined", although the server sent the right loan.

Start with what the server sends. JSON is a text format for data. It looks like a JavaScript object, and it is a string.

const text = '{"title":"Dune","daysLate":0,"reader":{"name":"Ines"}}';

console.log(typeof text);
console.log(text.title);

const loan = JSON.parse(text);
console.log(typeof loan);
console.log(loan.title);
console.log(loan.reader.name);
string
undefined
object
Dune
Ines
  1. text is a string. A string has no title property, so text.title is undefined.
  2. JSON.parse reads the text and builds a real object from it.
  3. After that, the dot works, including for nested objects.

JSON.stringify goes the other way, from an object to text. You use it to send data and to print an object in a log.

const loan = { title: "Dune", daysLate: 0 };
console.log(JSON.stringify(loan));
{"title":"Dune","daysLate":0}

JSON is stricter than JavaScript. Property names need double quotes, and a comma after the last item is an error. JSON.parse throws a SyntaxError on text that breaks those rules, such as an HTML error page that a server sent in place of JSON.

The body arrives later

A response object gives you the status at once. The body is different. It may still be arriving, so the method that reads and parses it returns a promise.

Here is a small stand-in for a response, shaped like the one Playwright and the browser's fetch give you.

const response = {
  status: 200,
  json() {
    return Promise.resolve({ loan: { title: "Dune", daysLate: 0 } });
  },
};

async function run() {
  const early = response.json();
  console.log(early.loan);

  const body = await response.json();
  console.log(body.loan.title);
}

run();
undefined
Dune

early is a promise. A promise has no loan property, so the first line prints undefined. One more dot, early.loan.title, is the error from the top of this lecture. With await, body is the parsed object.

In a Playwright API test it looks like this:

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

test('the API returns the loan', async ({ request }) => {
  const response = await request.get('/api/loans/12');
  expect(response.status()).toBe(200);

  const body = await response.json();
  expect(body.loan.title).toBe('Dune');
});

There are two awaits for one request. The first waits for the response to start. The second waits for the body. /api/loans/12 is a relative path, and Playwright puts the baseURL from its configuration in front of it.

Decide which fields to check

A response often has fields that change on every call, such as an id, a time or a token. Comparing the whole body with a fixed object fails on those, and the failure says nothing about the feature.

const body = { id: 4821, title: "Dune", daysLate: 0, updatedAt: "2026-05-01T09:30:00Z" };

console.log(body.title === "Dune" && body.daysLate === 0);
console.log(typeof body.id === "number");
console.log(typeof body.updatedAt === "string");
true
true
true

Check the exact value of the fields your test controls. For the fields it does not control, check that they are present and have the right kind. In Playwright, toMatchObject checks a subset of the fields and ignores the others.

Check the status as well, and check it first. A test that only reads the body can pass on an error response that happens to contain the right word.

Remember this

JSON is text, and JSON.parse turns it into an object. Reading a response body is asynchronous, so await response.json(). Check exact values for the fields your test controls, and the presence and kind of the ones it does not.

Reference: JSON on MDN.

now prove it

Reading is the setup. Solve this exercise in the editor. We run your code on each case and compare what it prints with the expected output.