SkillByAIOpen interactive version →

Lesson 21 / 25

API Testing

request fixture and cy.request.

HTTP calls from the test runner

Playwright's request fixture is an APIRequestContext that sends HTTP requests from Node, honours baseURL and extraHTTPHeaders, and returns responses you can inspect with status(), ok(), json(), or assert with await expect(response).toBeOK(). page.request shares cookies with the page's browser context. Cypress's cy.request(method, url, body) sends a request from the Cypress Node process (not through the app), automatically sends and stores cookies, and by default fails the test on 4xx/5xx responses unless failOnStatusCode: false is set. API calls are ideal for fast setup, cleanup and contract-level checks that do not need a UI.

Creating and verifying a resource

Playwright and Cypress side by side.

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

test('creates an issue via the API', async ({ request }) => {
  const created = await request.post('/api/issues', {
    data: { title: 'Broken link', priority: 'high' },
  });
  await expect(created).toBeOK();
  const issue = await created.json();

  const fetched = await request.get(`/api/issues/${issue.id}`);
  expect(await fetched.json()).toMatchObject({ title: 'Broken link', priority: 'high' });
});

// Cypress
it('creates an issue via the API', () => {
  cy.request('POST', '/api/issues', { title: 'Broken link', priority: 'high' })
    .then((res) => {
      expect(res.status).to.eq(201);
      return cy.request(`/api/issues/${res.body.id}`);
    })
    .its('body')
    .should('include', { title: 'Broken link' });
});

Mix API and UI in one test

Create data through the API, check it through the UI, and verify side effects through the API again. Each layer does what it is fastest at.

Quick check: By default, what does cy.request do when the response status is 500?

  • Retries forever
  • Fails the test, unless failOnStatusCode is set to false
  • Ignores the status silently
  • Converts it to a 200
Answer

Fails the test, unless failOnStatusCode is set to false — Turn the check off when testing error responses deliberately.