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 DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk6 min

How to Test APIs with Cypress: Part 1

Cypress can test a live API directly with cy.request()—no page visit required. Learn setup, assertions, error handling, request patterns, and when to use cy.intercept().
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Cypress’s cy.request() command to call a running API directly, then assert on its response. You do not need to open a web page first. Use cy.intercept() instead when you want to observe or stub requests made by your application in the browser; it does not intercept calls made with cy.request().

Set up a Cypress API spec

API-only specs still run as Cypress end-to-end tests. Configure an e2e.baseUrl to make requests with relative paths, or provide a complete URL to cy.request(). The example below assumes your API is running locally at port 3001 and has a GET /users endpoint. Replace the host, path, and expected response shape with your own service’s stable contract.

As an Amazon Associate I earn from qualifying purchases.

// cypress.config.js
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3001',
  },
})
// cypress/e2e/api/users.cy.js
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.be.an('array')
      expect(response.body.results).to.have.length.greaterThan(1)
    })
  })
})

Run just this spec with npx cypress run --spec 'cypress/e2e/api/users.cy.js'. Cypress’s API Testing guide documents this direct-request approach and additional examples.

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

Assert on the API contract

cy.request() yields a response you can inspect in .then(). Cypress automatically parses a response body as a JavaScript object when the content type indicates JSON. Check what matters to your endpoint rather than asserting incidental details that may change.

  • Status: Assert the expected success or error code.
  • Body: Verify required fields, types, collection shape, and meaningful domain outcomes.
  • Headers: Check contractually important headers, such as a content type or caching directive, when relevant.
  • Duration: The response includes duration, but a strict latency threshold is useful only when the environment and measurement goal make it meaningful. Cypress examples do not establish a universal API latency target.

By default, cy.request() fails when the response status is outside the 2xx/3xx range. For a test whose purpose is to verify an expected client or server error, opt out of that default and assert the result explicitly:

cy.request({
  method: 'GET',
  url: '/users/not-a-real-id',
  failOnStatusCode: false,
}).then((response) => {
  expect(response.status).to.eq(404)
  expect(response.body).to.have.property('error')
})

Use an error response and body that your API actually defines. Assertions chained directly to a Cypress command run once; they are not automatically retried as a way to wait for the server to become ready. The cy.request() reference describes its options and behavior.

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

What the test needs to prove Use What happens
The real endpoint responds correctly cy.request() Cypress sends a direct request from its Node process; no browser navigation is needed.
The app makes a request and you need to observe or wait for it cy.intercept() Cypress matches browser application traffic routed through its proxy.
The app behaves correctly for a controlled response cy.intercept() with a static response or handler The app can receive a stubbed response without contacting the real backend.
Node-side work such as database access or file I/O cy.task() The work is delegated to the Cypress Node process.

A cy.request() call bypasses cy.intercept(), does not appear as browser-originated Network traffic, and is not subject to browser CORS enforcement. Cypress documents that it participates in cookie handling with the browser’s cookie jar. For app-initiated traffic and stubbing, see cy.intercept() and Intercepting Network Requests.

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

Build useful API test patterns

Read an endpoint

Start with a GET request and assert stable contract fields, types, or collection structure. Avoid depending on incidental data such as a particular record unless the test controls that data.

Test a create/read/update/delete lifecycle

For a CRUD workflow, create a test record, capture the identifier returned by the API, and use that identifier for subsequent reads, updates, and deletion. Assert each meaningful state transition. Clean up test-created data when the service and test environment permit it; otherwise, use isolated test data or a resettable test environment so runs do not depend on leftover state.

Handle authentication

Send the authentication headers or credentials your API requires. If several specs need the same token setup, a custom Cypress command can centralize that work and reduce duplication. Keep secrets in suitable environment configuration rather than committing credentials to the repository. Cypress’s API guide demonstrates a custom cy.api() command using cy.env(); consult the documentation matching your installed Cypress version for the supported configuration details.

Use HTTP for setup, UI for user-visible behavior

Direct API calls can seed backend state more clearly or quickly than navigating setup screens. They can also verify backend state after an action. When the behavior that matters is what a user sees or does, retain a UI check for that behavior: an API assertion alone does not prove that the interface renders or responds correctly.

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

Keep the suite readable and efficient

Cypress starts a browser for each spec file, so the official performance guidance recommends grouping tests thoughtfully and suggests grouping specs by resource rather than by HTTP verb. API-only specs still use the end-to-end testing type. They can also help distinguish backend contract failures from UI selector or timing failures. See Cypress testing types and Optimizing Test Performance.

  • Use real requests when the test’s purpose is to verify the live endpoint.
  • Use stubs when the test’s purpose is to exercise the application’s response to a controlled server result.
  • Label these test types clearly: a passing stubbed UI test is not evidence that the live API contract works.
  • Group related resource checks where that makes setup and maintenance easier, without making tests depend on execution order.

Troubleshoot common failures

The spec cannot reach the endpoint

Check that the service is running, the configured baseUrl has the correct scheme, host, and port, and the relative path resolves to the intended route. If using an absolute URL, verify it directly in the request configuration.

An expected 4xx or 5xx makes the command fail

This is the default behavior when failOnStatusCode is true. Set it to false only for a test that intentionally checks a non-2xx/3xx response, then assert the expected status and error contract.

cy.intercept() does not see the request

Confirm whether the request was made by the application in the browser or directly with cy.request(). The latter bypasses cy.intercept(); assert on the yielded response instead.

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

The body is not the object the test expects

Inspect the response content type and actual body. Cypress automatically parses JSON when the content type ends in JSON; a different content type or an API response shape that differs from the assumed contract may require adjusting the assertion.

A request times out or a duration assertion is flaky

A timeout can occur while Cypress waits for the server response. Check service availability and response behavior, then choose a timeout appropriate to the endpoint and environment if needed. Avoid turning a single duration observation into a universal performance threshold; noisy or variable test environments can make strict limits brittle.

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

Or skip the browser setup

If the task is to capture a page rather than test an API contract, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns a screenshot or PDF. For example, this cURL call saves a WebP shot of Stripe:

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 are accepted and removed before capture, along with known newsletter popups and chat widgets; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server lets AI agents use screenshot tools, and the Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for the free plan.

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

Further scenarios and version notes

Cypress’s API guide and command reference also cover scenarios such as GraphQL, uploads, polling, and fixtures; add those patterns when your API or test case needs them rather than complicating a basic contract check. Documentation can change: consult the Cypress docs for your installed version. The cy.request() history records support for the QUERY method in version 15.20.0, so do not assume that method is available in older installations.

Frequently Asked Questions

Do Cypress API specs need to visit the application first?

No. An API spec can call an endpoint directly with cy.request() without loading an application page.

Can I use Cypress to verify an API and test the UI in one project?

Yes. Direct API checks and browser-based UI checks can complement one another, provided the test makes clear which behavior it proves.

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.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

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.