Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 35 ยท Network and Data

Testing APIs Directly

Test HTTP APIs without a browser: cy.request and the Playwright request fixture, assertions on status, headers and body, schema checks and API plus UI combos.

Not everything worth testing needs a browser. When you want to know whether POST /api/todos returns 201, rejects an empty title with 422, or sends the header your front end expects, clicking through a page is a slow and indirect way to find out. Both Cypress and Playwright can send HTTP requests straight from the test, without rendering anything. These API tests run in milliseconds, fail with clear messages, and can be mixed with UI tests: create the data through the API, then check it on screen.

In this lesson you will learn cy.request and Playwright's request fixture, what to assert on a response (status, headers, body), how to check the shape of a response with a schema, and how to combine API setup with UI verification. You already met API calls for setup in Test Data and Logging In Fast; here they become tests of their own.

A real server and the two tools cannot run on this site, so the Cypress and Playwright code is read-only. The runnable examples are stand-ins: a small HTTP server on your own loopback address (127.0.0.1) running inside the Node.js example, and a tiny test helper that mimics the style of real API tests. They are not the tools' code.

API tests and where they fit

An API test sits between a unit test and a browser test. It exercises the real server, including routing, validation and the database, but skips the page entirely. That makes it:

  • fast (no page load, no rendering),
  • precise (a failure points at the endpoint, not at "something on the page"),
  • stable (no selectors, no animations).
flowchart LR
  subgraph ui["UI test"]
    U["Browser + page"] --> A1["API"]
  end
  subgraph api["API test"]
    T["Test code"] --> A2["API"]
  end
  A1 --> D[("Server + database")]
  A2 --> D

An API test talks to the same server as a browser test, with the page left out.

They do not replace UI tests: an API test cannot tell you that the button is wired to the endpoint. But for validation rules, permissions, status codes and response formats, they are the cheapest tests you can write. Compare with the strategy in Testing Strategy and the Test Pyramid.

Sending requests in Cypress

cy.request() makes an HTTP request from the Cypress runner (not from the page), so it is not blocked by the browser's cross-origin rules. It shares cookies with the browser session, so after a login request the cookie is also there for cy.visit. Relative URLs use baseUrl from the config.

JavaScript
// Cypress (read-only)
describe('todos API', () => {
  it('creates a todo', () => {
    cy.request('POST', '/api/todos', { title: 'Buy milk' }).then((response) => {
      expect(response.status).to.eq(201)
      expect(response.headers['content-type']).to.include('application/json')
      expect(response.body).to.have.property('id')
      expect(response.body).to.include({ title: 'Buy milk', done: false })
    })
  })

  it('rejects an empty title', () => {
    cy.request({
      method: 'POST',
      url: '/api/todos',
      body: { title: '' },
      failOnStatusCode: false,        // do not fail the test just because the status is 4xx
    }).then((response) => {
      expect(response.status).to.eq(422)
      expect(response.body.error).to.eq('title is required')
    })
  })

  it('requires a token', () => {
    cy.request({ url: '/api/todos', failOnStatusCode: false, headers: { Authorization: 'Bearer wrong' } })
      .its('status')
      .should('eq', 401)
  })
})

By default, cy.request fails the test on any non-2xx or 3xx status, which is why tests of error responses pass failOnStatusCode: false. The response object has status, statusText, headers, body and duration. The values are plain data, so the assertion style is the usual expect(...).to... or .its('status').should('eq', 200). Remember from How Cypress Commands Really Work that you work with the response inside .then(), not through a variable.

Sending requests in Playwright

Playwright gives every test a request fixture: an HTTP client with the same baseURL as the browser. Calls return a response object that you await.

TypeScript
// Playwright (read-only)
import { test, expect } from '@playwright/test';

test('creates a todo', async ({ request }) => {
  const response = await request.post('/api/todos', { data: { title: 'Buy milk' } });

  expect(response.status()).toBe(201);
  expect(response.headers()['content-type']).toContain('application/json');
  const todo = await response.json();
  expect(todo).toMatchObject({ title: 'Buy milk', done: false });
  expect(todo.id).toBeGreaterThan(0);
});

test('rejects an empty title', async ({ request }) => {
  const response = await request.post('/api/todos', { data: { title: '' } });
  expect(response.status()).toBe(422);
  expect(await response.json()).toEqual({ error: 'title is required' });
});

test('is OK', async ({ request }) => {
  const response = await request.get('/api/todos');
  await expect(response).toBeOK();           // any status from 200 to 299
});

Differences from Cypress worth noting: a response with a 4xx or 5xx status does not throw by default (pass failOnStatusCode: true if you want that), header names in response.headers() are lowercase, and the body is read with await response.json() or await response.text(). To send a token on every call, put it in use: { extraHTTPHeaders: { Authorization: 'Bearer ...' } } in playwright.config.ts. The page.request object shares cookies with that page, so a login through it also logs in the browser tab.

What to assert

A useful API test checks more than the status code.

  • Status. 201 for creation, 204 for deletion with no content, 400 or 422 for invalid input, 401 when not logged in, 403 when not allowed, 404 for a missing item.
  • Headers. content-type, location after creation, caching headers, security headers when relevant.
  • Body. The fields you promise to clients, including their types. Prefer matching objects (toMatchObject, to.include) over comparing a whole response that contains timestamps or generated IDs.
  • Side effects. After a POST, a GET should show the new item; after a DELETE, a GET should return 404.
  • Negative cases. Missing fields, wrong types, too-long values, missing or wrong credentials. These are where bugs hide.

An API test in miniature

The stand-in below starts a real HTTP server inside the program, on 127.0.0.1 and a port the system chooses, and then tests it with Node's built-in fetch. The test and expectEqual helpers imitate the shape of the real tools. One test is wrong on purpose so you can see what a failure message looks like.

Node.js Testing a tiny todo API over loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first three tests pass, and the fourth fails with status: expected 200 but got 404. That message format (what was checked, what you expected, what you got) is what good API assertions should always give you. The second test shows the "negative case" idea: sending a blank title and expecting a clean 422 rather than a crash.

Checking the shape of a response

Equality checks on whole bodies break when harmless fields are added. A schema check describes the shape of a response (field names and types) and ignores the values. In real projects you would use a library such as Ajv (JSON Schema) or Zod; they are read-only here because no npm packages are available on this site. This stand-in implements the core idea by hand so you can see what such a library does for you.

Node.js A hand-written schema check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Three typical contract breaks show up: a number that became a string, a renamed field (reported both as a missing field and as an unknown one), and a date in the wrong format. A check like this inside every API test turns the response format into a contract between server and front end, which also tells you when a network stub has drifted away from the real API: validate your fixture with the same schema.

Combining API setup with UI checks

The most productive pattern mixes both: create the state through the API, then use the browser only to verify what a user sees.

JavaScript
// Cypress (read-only)
it('shows a todo created through the API', () => {
  cy.request('POST', '/api/todos', { title: 'Water the plants' })
  cy.visit('/todos')
  cy.contains('li', 'Water the plants').should('be.visible')
})
TypeScript
// Playwright (read-only)
test('shows a todo created through the API', async ({ page, request }) => {
  await request.post('/api/todos', { data: { title: 'Water the plants' } });
  await page.goto('/todos');
  await expect(page.getByRole('listitem').filter({ hasText: 'Water the plants' })).toBeVisible();
});

The reverse also works: do something in the UI, then call the API to confirm the server stored the right thing (for example, after submitting a form, GET the record and compare). The finished version of this approach is the project Combine API Setup with UI Checks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main reason to test validation rules with API tests instead of browser tests?

    An API test skips the page, so it runs in milliseconds and fails with a message about the endpoint, not about the UI.
  2. 2. By default, what does cy.request do when the server answers with status 422?

    cy.request treats non-2xx and non-3xx statuses as failures by default. Tests for error responses turn that off with failOnStatusCode: false.
  3. 3. Which Playwright call returns the parsed JSON body of a response?

    response.json() is asynchronous. Remember the await.
  4. 4. A response gained a new field 'createdAt'. Which kind of check keeps passing, if you only care about the fields you promised?

    Matching only the promised fields tolerates harmless additions, while a whole-body comparison breaks on every new field.
  5. 5. Which is a good use of both an API call and the browser in one test?

    API setup is quick and reliable, and the UI check verifies only what the test is about.

Summary

  • API tests call the server directly: fast, precise and stable, but they cannot prove the UI is wired correctly.
  • Cypress: cy.request(method, url, body) or an options object; use failOnStatusCode: false for expected errors and work with the response in .then().
  • Playwright: the request fixture, await response.json(), response.status(), await expect(response).toBeOK(); 4xx and 5xx do not throw by default.
  • Assert status, headers, body fields, side effects and negative cases, not just "it returned 200".
  • Schema checks (Ajv, Zod in real projects) turn a response format into a contract and help keep stubs honest.
  • Combine API setup with UI verification for fast, focused tests.
  • The stand-ins use a loopback server and hand-written helpers; they are not the real tools.

Next: Hooks, Fixtures and Custom Commands