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 desk7 min

How to Test APIs with Cypress: cy.request(), cy.intercept(), and Practical Patterns

Use cy.request() for direct API calls and cy.intercept() for browser traffic. This guide shows how to assert responses, manage errors, seed test data, and troubleshoot common Cypress API test failures.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use cy.request() to call an API endpoint directly and assert on its response. Use cy.intercept() to observe or stub requests made by your application in the browser. They solve different problems: a direct cy.request() call is not browser traffic and cannot be caught by cy.intercept().

Write a basic Cypress API test

Cypress documents API tests as part of its end-to-end testing type. Configure a baseUrl to avoid repeating the API host, then call the endpoint and assert against the response:

As an Amazon Associate I earn from qualifying purchases.

describe('GET /users', () => {
  it('returns a list of users', () => {
    cy.request('GET', '/users').then((response) => {
      expect(response.status).to.eq(200)
      expect(response.body.results).to.have.length.greaterThan(1)
    })
  })
})

For example, put the host in Cypress configuration:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'https://api.example.test'
  }
})

Replace the example host and expected response shape with values from your own API contract and controlled test data. A baseUrl is optional: use an absolute URL instead. A relative URL resolves against the configured baseUrl, or against the host of a page already visited if no base URL is configured.

Cypress supports cy.request(url), cy.request(url, body), cy.request(method, url), cy.request(method, url, body), and cy.request(options). The options form is useful when the test needs headers, authentication, or behavior overrides.

Assert the parts of the response that matter

Tests can check status, fields, headers, and request duration. Keep assertions tied to the API contract rather than incidental fixture details:

cy.request('/users/1').then((response) => {
  expect(response.status).to.eq(200)
  expect(response.body).to.have.property('email')
  expect(response.duration).to.be.lessThan(1000)
})

The duration threshold here is an example, not a universal service-level target. Set one that is meaningful in your test environment; otherwise, it can make a test flaky without expressing a real requirement.

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

Choose between cy.request(), cy.intercept(), and cy.task()

Command Use it for Request origin or work location
cy.request() Call an endpoint directly, set up data, or validate a real API response. Runs outside the browser proxy from Cypress’s Node process.
cy.intercept() Observe, wait for, or stub a request triggered by the application. Matches browser application traffic; the response can pass through or be controlled.
cy.task() Perform setup requiring direct database access, file I/O, or other Node-side work. Runs a task in Node from the test.

Because cy.request() does not run as browser traffic, it does not appear in the browser Network tab, and cy.intercept() cannot spy on or stub it. CORS and browser same-origin restrictions do not apply to that direct request. Cypress sends matching browser cookies with the request and reflects response Set-Cookie values into the browser cookie jar, so API login or setup can share state with later UI actions.

Use cy.intercept() when the question is about what the front end sends or how it handles a response. Register the intercept before the UI action that triggers the request:

cy.intercept('GET', '/api/users').as('getUsers')
cy.visit('/users')
cy.wait('@getUsers').its('response.statusCode').should('eq', 200)

Use a real response when verifying the integrated backend. Stub a response when you need a deterministic edge case or a state that is difficult to create reliably. Cypress supports mixing real and stubbed traffic in a suite; choose per test according to what it is meant to prove.

Build useful API coverage

Seed data and verify persisted changes

Direct API calls are useful for creating or resetting data before opening the application. A cross-layer test can seed through the API, exercise the UI, then query the API to confirm the change persisted. This checks integration without forcing every setup step through the interface.

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

Cover validation, authorization, and boundaries

Test invalid input, permission boundaries, rate limits, and pagination edges when those behaviors are part of the API contract. These cases may be awkward to reach through a form, but tests should reflect cases the service actually supports rather than inventing endpoints or expectations.

Make error responses explicit

By default, cy.request() fails when the response status is outside the 2xx/3xx range. If an error response is the behavior under test, disable that default and assert the result deliberately:

cy.request({
  method: 'POST',
  url: '/users',
  body: { email: 'not-an-email' },
  failOnStatusCode: false
}).then((response) => {
  expect(response.status).to.eq(422)
  expect(response.body).to.have.property('error')
})

Centralize repeated authentication and setup

If many tests need the same API prefix or authorization header, wrap that setup in a custom Cypress command rather than copying options into every test. Keep hosts and credentials environment-specific, using Cypress configuration or environment variables instead of committing secrets into test code.

Put large request payloads in fixtures and load them where needed. For values passed between Cypress commands, use aliases or the yielded chain value; do not treat Cypress commands as synchronous functions that return ordinary values for assignment.

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

Understand request defaults and version-sensitive behavior

  • Redirects: Cypress follows redirects by default. Set followRedirect: false if the test needs to inspect the redirect response or its Location behavior.
  • Retries: Cypress documentation says transient network errors are retried by default up to four times; status-code failures are not retried unless configured. Confirm the behavior in the documentation for the Cypress version used by your project.
  • Timeout: cy.request() uses responseTimeout, not defaultCommandTimeout. Override the request with timeout when a particular endpoint needs a different limit.
  • Body serialization: Object and Boolean request bodies are JSON-serialized and receive an application/json content type. String bodies are sent as-is and do not automatically receive a content type.
  • Browser cache: A response served from cache may not reach the network layer, so it may not trigger cy.intercept(). Disabling cache headers in the test environment is one documented workaround.
  • Native interception: Cypress’s network guide says that starting in Cypress 16, Chrome, Chromium, and Edge intercept test traffic on the native browser network. This concerns interception of browser traffic, not direct cy.request() calls. Check the current guide for your Cypress version and browser.

Keep API tests reliable and efficient

API tests validate endpoint behavior without page rendering or simulated interaction, making them useful for focused contract checks and efficient setup. They do not replace UI tests, which cover user interactions, rendering, and the experience of using the application. A balanced suite can authenticate or seed by HTTP, perform the user action in the UI, and verify the resulting state through an API request.

Cypress starts a browser per spec file. Group related API tests in a spec where sensible so browser startup is amortized, rather than creating a separate spec for every small request without a reason. Keep tests independent by controlling their data and reset strategy; use an API endpoint for API setup and cy.task() when setup truly needs direct Node access to a database or files.

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

Troubleshoot common API test failures

Symptom Likely cause Fix
A 4xx or 5xx response fails the command before assertions run. failOnStatusCode is enabled, as it is by default. Set failOnStatusCode: false only for the test that expects the error, then assert on its status and body.
A relative endpoint resolves to the wrong host. The test has no intended baseUrl, or a prior page visit supplied a different host. Configure the API baseUrl or pass the full endpoint URL.
An intercept never sees the request. The request was made with cy.request(), happened before intercept registration, or was served from browser cache. For direct calls, assert on the cy.request() response. For UI traffic, register cy.intercept() before the triggering action; investigate cache behavior if needed.
A request times out. The response exceeded the configured response timeout or the environment is slow/unavailable. Check the endpoint and test environment, then adjust the request’s timeout only where a longer response is expected.
A string payload is rejected or parsed incorrectly. Strings are sent as-is and do not automatically receive a content type. Send the expected content type header and format the body according to the endpoint contract.
A redirect assertion sees the final page instead of the redirect. Redirect following is on by default. Set followRedirect: false and inspect the returned redirect response.

Or skip the browser setup

For a screenshot of an API’s documentation or a web page used in your test workflow, ScreenshotNeo is a website screenshot API and MCP server—not a replacement for Cypress API assertions. Its one-call HTTP API returns an image or PDF:

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 banners and consent overlays, newsletter popups, and chat widgets are handled before capture; those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, with response headers indicating the page verdict and billing status. An MCP server exposes screenshot, page-info, and PDF capture tools to AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for ScreenshotNeo’s free plan.

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.

Further reading

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.