---
title: Asserting Status, Headers and JSON | TestingBot
description: An API test is only as good as its assertions. &quot;The request did
  not throw&quot; proves little; &quot;the search returned only matching products,
  each…
source_url:
  html: https://testingbot.com/resources/courses/playwright-api-testing/asserting-status-headers-and-json
  md: https://testingbot.com/resources/courses/playwright-api-testing/asserting-status-headers-and-json.md
---

Course

[Playwright API Testing Tutorial](https://testingbot.com/resources/courses/playwright-api-testing)

Chapter 3 of 9

1. [1 Playwright API Testing: a Hands-On Course](https://testingbot.com/resources/courses/playwright-api-testing)
2. [2 The request Fixture and APIRequestContext](https://testingbot.com/resources/courses/playwright-api-testing/the-request-fixture)
3. [3 Asserting Status, Headers and JSON](https://testingbot.com/resources/courses/playwright-api-testing/asserting-status-headers-and-json)
4. [4 Authentication: Tokens, Test Accounts and storageState](https://testingbot.com/resources/courses/playwright-api-testing/authentication-and-tokens)
5. [5 Test Data Setup and Teardown Through the API](https://testingbot.com/resources/courses/playwright-api-testing/test-data-setup-through-the-api)
6. [6 Schema Validation with zod and ajv](https://testingbot.com/resources/courses/playwright-api-testing/schema-validation)
7. [7 Mocking APIs with page.route](https://testingbot.com/resources/courses/playwright-api-testing/mocking-with-page-route)
8. [8 Running API and UI Tests in CI and on a Cloud Grid](https://testingbot.com/resources/courses/playwright-api-testing/ci-and-the-cloud-grid)
9. [9 Knowledge Check](https://testingbot.com/resources/courses/playwright-api-testing/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 3 of 9 Intermediate 7 min read 3 quick checks Updated Nov 2026 

# Asserting Status, Headers and JSON
On this page
1. [Status codes: toBeOK and its limits](https://testingbot.com#status-codes-tobeok-and-its-limits)
2. [Typing the JSON](https://testingbot.com#typing-the-json)
3. [Asserting on the body](https://testingbot.com#asserting-on-the-body)
4. [Headers](https://testingbot.com#headers)
5. [Make failures explain themselves](https://testingbot.com#make-failures-explain-themselves)

An API test is only as good as its assertions. "The request did not throw" proves little; "the search returned only matching products, each with a price" proves the feature works. This chapter covers the assertions that matter, how to type the JSON you get back, and how to make a failure tell you what went wrong without rerunning anything.

## Status codes: toBeOK and its limits[#](https://testingbot.com#status-codes-tobeok-and-its-limits)

Playwright adds one API-specific matcher to `expect`: `toBeOK()`, which passes for any status from 200 to 299. When it fails, the error includes the full request and response log:

```
Error: expect(response).toBeOK() failed

Call log:
→ GET https://api.practicesoftwaretesting.com/products/does-not-exist
  user-agent: Playwright/1.65.0 (arm64; macOS 26.4) node/22.18
  accept: application/json
  accept-encoding: gzip,deflate,br
← 404 Not Found
```

That log is the reason to prefer it over `expect(response.ok()).toBe(true)`, which fails with an unhelpful "expected true, received false". Notice the `accept: application/json` line: that is the `extraHTTPHeaders` from the project config at work.

`toBeOK()` is deliberately loose, though. When the exact status matters, assert it: a create endpoint that answers `200` instead of `201`, or `204` where a client expects a body, is a real contract change.

```typescript
expect(response.status()).toBe(201);
```

And remember the opposite case. By default Playwright does **not** throw on 4xx or 5xx responses: it hands you the response so you can test error handling. If you would rather have every unexpected error status fail loudly, pass `failOnStatusCode: true` to a request (or set it on a context you create). The error then contains the response body as well:

```
Error: apiRequestContext.get: 404 Not Found
Response text:
{"message":"Requested item not found"}
```

A teammate's test does `await request.delete('/orders/42')` and nothing else. The endpoint has been returning `500` for a week, yet the test is green. Why?

 Playwright returns 4xx and 5xx responses instead of throwing, and the test never checks the status `DELETE` responses are always treated as successful The test needs `await expect(response).toBeVisible()`

Unless you pass `failOnStatusCode: true`, a 500 is just a response object. A request with no assertion on it passes no matter what the server says.

## Typing the JSON[#](https://testingbot.com#typing-the-json)

`response.json()` returns `Promise<any>`. That is convenient and dangerous: a typo in a field name compiles fine and fails at runtime, or worse, compares `undefined` to `undefined` and passes. Give the shape a name. Create `lib/types.ts`:

```typescript
export type Product = {
  id: string;
  name: string;
  price: number;
  in_stock: boolean;
  category: { id: string; name: string; slug: string };
  brand: { id: string; name: string };
};

export type Page<T> = {
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
  data: T[];
};
```

Annotating the result of `json()` with these types gives you autocompletion and catches typos at compile time. It does **not** check anything at runtime: TypeScript believes you. Chapter 5 replaces these hand-written types with a schema that checks the data and produces the type at the same time.

## Asserting on the body[#](https://testingbot.com#asserting-on-the-body)

Create `tests/api/products.spec.ts`:

```typescript
import { test, expect } from '@playwright/test';
import type { Page, Product } from '../../lib/types';

test('search returns only matching products', async ({ request }) => {
  const response = await request.get('/products/search', {
    params: { q: 'pliers' },
  });

  await expect(response).toBeOK();
  expect(response.headers()['content-type']).toContain('application/json');

  const body: Page<Product> = await response.json();
  expect(body.total).toBe(body.data.length);
  for (const product of body.data) {
    expect(product.name.toLowerCase()).toContain('pliers');
    expect(product.price).toBeGreaterThan(0);
  }
});

test('first page has the shape the shop relies on', async ({ request }) => {
  const response = await request.get('/products', { params: { page: 1 } });
  const body: Page<Product> = await response.json();

  expect(body).toMatchObject({ current_page: 1, per_page: 9 });
  expect(body.data[0]).toEqual(
    expect.objectContaining({
      id: expect.any(String),
      name: expect.any(String),
      price: expect.any(Number),
      category: expect.objectContaining({ slug: expect.any(String) }),
    }),
  );
});

test('unknown product is a 404 with a message', async ({ request }) => {
  const response = await request.get('/products/does-not-exist');

  expect(response.status()).toBe(404);
  expect(await response.json()).toEqual({ message: 'Requested item not found' });
});

test('failOnStatusCode turns a 404 into an exception', async ({ request }) => {
  await expect(
    request.get('/products/does-not-exist', { failOnStatusCode: true }),
  ).rejects.toThrow(/404/);
});
```

```
Running 4 tests using 4 workers

  ✓ 2 [api] › tests/api/products.spec.ts:35:1 › unknown product is a 404 with a message (179ms)
  ✓ 3 [api] › tests/api/products.spec.ts:42:1 › failOnStatusCode turns a 404 into an exception (179ms)
  ✓ 1 [api] › tests/api/products.spec.ts:4:1 › search returns only matching products (184ms)
  ✓ 4 [api] › tests/api/products.spec.ts:20:1 › first page has the shape the shop relies on (206ms)

  4 passed (639ms)
```

The matchers worth knowing, and when each one fits:

- **`toEqual`** compares the whole value recursively. Use it for small, fully known bodies such as the error message above. On a large body it is brittle: any new field the API adds breaks the test, even though no client cares.
- **`toMatchObject`** checks only the properties you list and ignores the rest. Good for "the page metadata says page 1, nine per page".
- **`expect.objectContaining`, `expect.any(Number)`, `expect.stringMatching(/.../)`** describe a shape instead of exact values. They are the right tool for data you do not control, like ids and generated timestamps, which change between runs.
- **Loops with plain assertions** , as in the search test, express rules that must hold for every item. They are the assertions most likely to catch a real bug: here, a search that starts returning unrelated products.

The search test also checks `total` against the number of items. That kind of internal consistency check is cheap and catches pagination bugs that a "status is 200" test never would.

A test asserts `expect(await res.json()).toEqual({ id: 7, name: 'Saw', price: 9.99 })`. The backend team adds a `created_at` field and the test fails, although no client is affected. What is the better assertion?

 Delete the assertion; the status check is enough Add `created_at` with today's date to the expected object Compare `JSON.stringify` of both objects `toMatchObject({ id: 7, name: 'Saw', price: 9.99 })`, which ignores fields you did not list

`toMatchObject` checks the fields you care about and tolerates additions, which are backwards compatible. A hard-coded timestamp would break tomorrow, and stringify comparison is even stricter than `toEqual`.

## Headers[#](https://testingbot.com#headers)

`response.headers()` returns an object with lower-case header names, so `headers()['content-type']` works whatever case the server used. Assert on headers that clients depend on: `content-type` (a JSON API that suddenly returns `text/html` usually means an error page from a proxy), caching headers on endpoints a CDN caches, `location` after a create, and security headers such as CORS rules if a browser front end calls the API.

Use `toContain` rather than `toBe` for `content-type`, because servers legitimately append a charset (`application/json; charset=utf-8`).

## Make failures explain themselves[#](https://testingbot.com#make-failures-explain-themselves)

When an assertion deep in a loop fails, "expected 0 to be greater than 0" is not much to go on. Every `expect` accepts a custom message as its second argument, and it is worth adding when the default output would not tell you which item or request was wrong:

```typescript
expect(response.status(), await response.text()).toBe(201);
```

Passing the response text as the message means a failed create shows the server's validation errors right in the report. The fixtures in chapter 3 use exactly this line.

For the full request and response of a failing test, turn on tracing. The trace viewer shows API calls made through any request context with their headers and bodies, just like browser network requests; [chapter 5 of the Playwright course](https://testingbot.com/resources/courses/playwright/debugging-tests) shows how to open it.

You annotate `const body: Product = await response.json()`. The API renames `price` to `unit_price`. What happens?

 TypeScript reports a compile error on the next run Nothing at compile time; `body.price` is `undefined` at runtime, and only an assertion on it will notice `response.json()` throws because the shape does not match Playwright converts the field name automatically

A type annotation is a promise you make to the compiler, not a runtime check. `json()` returns whatever the server sent. Chapter 5 adds a schema that does check it.

Next: every useful API has endpoints that need a logged-in user. Chapter 3 gets a token and shares it between API calls and the browser.

[Previous · Chapter 2 The request Fixture and APIRequestContext](https://testingbot.com/resources/courses/playwright-api-testing/the-request-fixture) [Next · Chapter 4 Authentication: Tokens, Test Accounts and storageState](https://testingbot.com/resources/courses/playwright-api-testing/authentication-and-tokens)

On this page

1. [Status codes: toBeOK and its limits](https://testingbot.com#status-codes-tobeok-and-its-limits)
2. [Typing the JSON](https://testingbot.com#typing-the-json)
3. [Asserting on the body](https://testingbot.com#asserting-on-the-body)
4. [Headers](https://testingbot.com#headers)
5. [Make failures explain themselves](https://testingbot.com#make-failures-explain-themselves)

Certification

Earn the free, resume-worthy TestingBot Playwright API Testing Certification for this course.

[How it works](https://testingbot.com/resources/courses/playwright-api-testing/certification)
