October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Test APIs with Cypress: Part 2

Use cy.request() for direct endpoint calls and response assertions; use cy.intercept() for browser traffic you need to observe, wait for, or stub.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use cy.request() to call a real endpoint and assert on its response. Use cy.intercept() to observe, wait for, or stub requests made by the application in the browser. The distinction matters: Cypress sends cy.request() from its Node process, outside the browser proxy, so an intercept cannot catch it.

Choose the Cypress command that matches the test

Test need Command What it does
Call an endpoint and check its actual response cy.request() Sends a request to a real endpoint and yields a response for assertions. It does not pass through cy.intercept().
Observe, wait for, or control traffic caused by the app cy.intercept() Matches browser requests. It can passively spy on them or return a stubbed response.
Run Node-side work such as file I/O or a database query cy.task() Runs work that is neither a browser request nor a direct endpoint assertion.

Use the direct request for backend contract checks, setup, or cleanup exposed through a safe test endpoint. Use an intercept when the behavior under test includes the browser making a request—for example, whether clicking Save sends the right request and how the page responds.

As an Amazon Associate I earn from qualifying purchases.

Make a direct API request with cy.request()

Set baseUrl in the Cypress end-to-end configuration to use relative paths. It is optional if you provide a complete URL. For example, with an API available under the configured base URL:

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.
cy.request('GET', '/users').then((response) => {
  expect(response.status).to.eq(200)
  expect(response.body.results).to.have.length.greaterThan(1)
})

The status and array length above illustrate assertions; use the contract your endpoint actually promises. The response also provides fields such as body, headers, and duration. Prefer stable contract checks—expected status, required fields, validation results, or authorization behavior—over incidental values that may change between runs.

Request forms and options

The command reference documents request forms including a URL, a method and URL, or an options object. Choose the form that makes the method, target, and required request settings clear in your test. For authentication or other headers, follow the endpoint’s actual contract; do not assume every application uses cookie authentication.

Cookies and authentication

Cypress documents that cy.request() attaches matching cookies and applies response Set-Cookie values to the browser cookie jar. This can make it useful for authenticated setup or assertions, but verify that this matches the application’s real authentication model.

Observe or stub browser requests with cy.intercept()

Register the intercept before the action that triggers the request, give it an alias, perform the action, then wait for the alias and inspect the captured request or response. The following pattern is illustrative; use the actual method, URL, and page action in your app:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cy.intercept('GET', '/api/users').as('getUsers')
cy.visit('/users')
cy.wait('@getUsers').then((interception) => {
  expect(interception.response.statusCode).to.eq(200)
})

An intercept can spy without changing the request, or stub a controlled response. Use a stub when a test needs a deterministic response or a condition that is difficult to obtain from the server. Keep stub expectations aligned with the API contract, and retain tests that exercise the real server where server behavior itself matters.

Interceptions are cleared before each test. Define them in each test or in an appropriate setup hook rather than expecting a route configured in one test to remain active in another.

Why cy.intercept() cannot catch cy.request()

cy.request() runs through Cypress’s Node process and bypasses the proxy used for browser traffic. cy.intercept() matches requests from the browser application, so it cannot spy on or stub a direct Cypress request. As Cypress’s API-testing guide puts it, “The browser is never asked to make the call.” If you need to inspect a direct request, assert on the response yielded by cy.request(); if you need to test app traffic, trigger that traffic in the browser and intercept it.

Use API calls to set up and verify UI workflows

A useful end-to-end test can combine both approaches: prepare server state with a direct API call, carry out only the user behavior that matters in the browser, and make another API call to verify the resulting persisted state. This avoids spending UI steps on setup unrelated to the behavior under test while still checking the server-side result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Prepare the required test state with cy.request() against a safe seed or setup endpoint.
  2. Register any needed cy.intercept() before the browser action that triggers the request.
  3. Perform the user workflow and wait for the aliased browser request if its behavior is part of the test.
  4. Use a final direct request when the test needs to confirm that the expected change persisted on the server.

Keep test data isolated and clean it up where needed. Only use seed or cleanup endpoints in an environment designed for testing.

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

Other API-testing patterns

  • Validation and permissions: Direct requests can exercise invalid input and permission boundaries that may be awkward to reach through a form. Assert the documented response and relevant error fields.
  • Fixtures: Cypress documentation describes recording fixtures and stubbing request or response properties. Treat fixtures as controlled test inputs, not proof that the live service behaves the same way.
  • GraphQL, uploads, and polling: Cypress’s API-testing guide covers these patterns, but the correct request shape and assertions depend on the service contract; a REST example should not be assumed to fit them.

Debug failures and avoid misleading results

When a direct request fails

Inspect the cy.request() entry in Cypress’s Command Log. Cypress documents that the entry can expose request and response details, including headers and bodies; the response also includes fields such as status, duration, headers, and body. In recorded CI runs, Test Replay can show command details. Do not copy secrets from headers or response bodies into public logs or examples.

When an intercept does not fire

  • Confirm the intercept matches the actual HTTP method and URL.
  • Register it before the page action that triggers the request.
  • Check that the browser request really occurs; a cached result or a different app path may mean the expected request was never sent.
  • Configure the intercept in the current test or its setup hook, since intercepts clear before each test.

For intermittent requests, wait on the matching alias rather than adding an arbitrary fixed delay.

Do not use a direct request to prove browser CORS behavior

cy.request() bypasses browser CORS enforcement. A successful direct request therefore does not prove that browser policy permits the same cross-origin request. To test that behavior, use a browser-driven flow and follow Cypress’s cross-origin guidance.

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

Or skip the browser setup

For a screenshot rather than an API test, ScreenshotNeo offers a one-request alternative to setting up browser automation. Its API can return a screenshot or PDF; this example saves a WebP image:

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 the request options. Cookie banners, popups, and chat widgets are removed before capture; bot checks, blank pages, timeouts, and failed loads are not billed. An MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Learn about ScreenshotNeo, then sign up for 1,000 free screenshots a month with no card.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
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.