Cypress 23 ๐ฒ API Testing โ cy.request and backend endpoint validation
Cypress is best known as a browser automation tool, but its cy.request command turns it into a capable API testing client as well. The command makes an HTTP request from the Cypress Node process, bypassing the browser’s security restrictions entirely, and yields the response object so that assertions can run against the status, headers, and body. This is the command that lets a single Cypress suite test both the frontend and the backend it talks to, without switching to a separate tool like Postman or a standalone HTTP client.
The important distinction is that cy.request is not a browser fetch. It runs outside the browser, so it is not subject to CORS, it does not trigger the application’s interceptors, and it does not appear in the Network tab of the browser’s DevTools. It is a direct HTTP call from the Node side of Cypress, and the response it yields is a plain object with status, body, headers, and duration properties. That makes it ideal for setting up state, validating endpoints, and testing the API layer independently of the UI.
This chapter covers the cy.request command in its three forms, the way it handles authentication and cookies, the pattern of using it to seed state before a UI test, and the assertions that run against the response. The sections that follow walk through the command signature, the request options, and the patterns that keep API tests reliable and independent.
Key point: cy.request makes an HTTP call from the Cypress Node process, not the browser, so it bypasses CORS, does not trigger the app’s interceptors, and yields a response object with status, body, headers, and duration that assertions can run against directly.
Why API testing inside Cypress exists
The frontend-backend gap problem. A UI test that clicks through a form and waits for a success message is testing the frontend, the backend, and the network between them all at once. When it fails, the failure could be in any of the three layers, and the debugging session starts by trying to figure out which one. A direct cy.request to the endpoint isolates the backend, and a UI test that uses cy.request to seed its data isolates the frontend. The gap between the two layers is where most flaky tests live, and cy.request is the tool that closes it.
The setup speed problem. A test that creates its data by clicking through the UI spends most of its time on the setup, not on the assertion. If the test is about a delete button, the five steps that create the record first are overhead. cy.request creates the record in a single call, and the UI test starts at the state it actually wants to verify. The setup becomes a single line instead of a multi-step flow, and the test runs faster and fails for the right reason.
The CORS problem. A browser fetch to a different origin is blocked by CORS unless the server sends the right headers, and a test that runs in the browser inherits that restriction. cy.request runs in the Node process, outside the browser’s security model, so it can call any endpoint the machine can reach. That is why it can hit a backend directly during a test even when the frontend’s origin is different.
The cookie and session problem. A login flow that goes through the UI takes a page load, a form fill, a submit, and a redirect. cy.request can post the credentials to the login endpoint and receive the session cookie directly, and Cypress stores that cookie in the browser’s cookie jar so the subsequent cy.visit is already authenticated. The login becomes one request instead of a UI flow.
The contract problem. The API’s response shape is a contract, and a test that only exercises it through the UI never checks the contract directly. The UI might read one field and ignore the rest, so a breaking change to a field the UI does not use goes undetected. A direct cy.request assertion on the body checks the whole contract, and the API test catches the break before the UI test does.
The trade-off. cy.request does not exercise the browser’s network stack, so it will not catch a CORS misconfiguration, a service worker interception, or a browser-level caching issue. It tests the endpoint, not the browser’s path to the endpoint. A suite that needs to verify the browser’s network behavior uses cy.intercept and a real page load, and cy.request is the complement for the endpoint itself.
a. The command signature and the three forms
cy.request has three forms. The first is a single URL string, which makes a GET by default. The second is a method and URL pair, which sets the HTTP method explicitly. The third is an options object, which carries the method, URL, body, headers, and query parameters together. All three yield the response object.
// Form 1: a plain URL, defaults to GET
cy.request("/api/users").then((response) => {
expect(response.status).to.eq(200); // the status is a number
});
// Form 2: method and URL
cy.request("POST", "/api/users", { name: "Alice" }).then((response) => {
expect(response.status).to.eq(201); // created
});
// Form 3: the options object
cy.request({
method: "PUT", // the HTTP method
url: "/api/users/1", // the endpoint
body: { name: "Alice Updated" }, // the JSON body, serialized automatically
headers: { "X-Trace-Id": "abc" }, // custom headers
qs: { expand: "roles" }, // query string parameters
}).then((response) => {
expect(response.body.name).to.eq("Alice Updated"); // the parsed JSON body
});
The options object is the form that scales. The body is serialized to JSON automatically when the content type is JSON, the qs object is appended to the URL as query parameters, and the headers object is merged into the request. The failOnStatusCode option, which defaults to true, decides whether a non-2xx status fails the test. Setting it to false lets the test assert on a 404 or a 500 explicitly.
// Assert on a 404 without the command failing the test
cy.request({
url: "/api/users/9999",
failOnStatusCode: false, // the 404 is expected, so do not fail
}).then((response) => {
expect(response.status).to.eq(404); // the endpoint returned not found
expect(response.body.error).to.eq("Not Found"); // the error body
});
The response object is the same for every form. The status is a number, the body is the parsed JSON when the response is JSON, the headers is an object of header names to values, and the duration is the request time in milliseconds. The requestHeaders and redirects properties are also present when they are relevant.
b. Authentication, cookies, and the session
The most common use of cy.request outside of pure API testing is the login shortcut. The test posts the credentials to the login endpoint, the server responds with a session cookie, and Cypress stores that cookie in the browser’s cookie jar. The next cy.visit is already authenticated, and the test skips the UI login flow entirely.
// Log in through the API and let Cypress store the session cookie
beforeEach(() => {
cy.request({
method: "POST",
url: "/api/login", // the login endpoint
body: { username: "alice", password: "secret" }, // the credentials
}).then((response) => {
expect(response.status).to.eq(200); // the login succeeded
// the Set-Cookie header is stored automatically in the cookie jar
});
});
it("shows the dashboard to a logged-in user", () => {
cy.visit("/dashboard"); // already authenticated
cy.contains("Welcome, Alice"); // the UI sees the session
});
The cookie storage is automatic for the default cypress.config setup, because cy.request and the browser share the same cookie jar. The cy.session command, introduced in Cypress 10, is the newer and more explicit way to cache the login across tests. It wraps the login logic and restores the cookies and localStorage for every test in the block, and it invalidates the cache when the session changes.
// The modern pattern: cache the login with cy.session
beforeEach(() => {
cy.session("alice", () => {
cy.request("POST", "/api/login", {
username: "alice",
password: "secret",
}).then((response) => {
expect(response.status).to.eq(200); // validated once, then cached
});
});
});
The auth option is the other way to send credentials. The auth: { username, password } object sends HTTP Basic authentication, and the auth: { bearer: token } form sends a Bearer token in the Authorization header. The headers option is the general escape hatch for any other scheme.
// Bearer token authentication
cy.request({
url: "/api/profile",
auth: { bearer: Cypress.env("API_TOKEN") }, // the token from the environment
}).then((response) => {
expect(response.status).to.eq(200); // authorized
});
c. Seeding state and asserting the contract
The pattern that makes UI tests reliable is to seed the data with cy.request and then verify the UI against the known state. The test does not click through the creation flow, so a failure in the creation flow does not fail the delete test, and the delete test starts from an exact record it created.
// Seed a record through the API, then test the UI against it
it("deletes a user from the list", () => {
cy.request("POST", "/api/users", {
name: "Temp User", // the record the test will delete
email: "temp@example.com",
}).then((response) => {
const userId = response.body.id; // the id the API assigned
cy.visit("/users"); // load the list page
cy.contains("Temp User") // the seeded record is visible
.parent() // the row container
.find("[data-cy=delete]") // the delete button in the row
.click(); // trigger the delete
cy.contains("Temp User").should("not.exist"); // gone from the list
cy.request(`/api/users/${userId}`).then((res) => {
expect(res.status).to.eq(404); // the backend actually deleted it
});
});
});
The contract assertion is the pure API test. It checks the status, the body shape, and the headers without touching the UI, and it is the test that catches a backend change before the frontend does. A suite of these covers the endpoints the app depends on, and they run fast because each one is a single request.
// A pure API contract test
it("returns the user with the expected shape", () => {
cy.request("/api/users/1").then((response) => {
expect(response.status).to.eq(200); // the happy path
expect(response.headers["content-type"]) // the content type
.to.include("application/json");
expect(response.body).to.have.keys( // the full contract
"id", "name", "email", "createdAt"
);
expect(response.body.id).to.be.a("number"); // the id is a number
expect(response.body.email).to.match(/@/); // the email looks valid
});
});
The cy.request chain is also the way to test an endpoint that the UI does not expose. A webhook receiver, an admin-only endpoint, or a health check is reachable with a single request, and the test verifies it without needing a page for it. The failOnStatusCode: false option is what lets the test assert on the error paths, which are the paths the UI rarely exercises.
Complete Example Session
// ============================================
// PART 1: THE BASIC REQUEST
// ============================================
describe("Users API", () => {
it("lists users", () => {
cy.request("/api/users").then((response) => {
expect(response.status).to.eq(200); // the list endpoint is healthy
expect(response.body).to.be.an("array"); // the body is an array
expect(response.body.length).to.be.greaterThan(0); // it has records
});
});
// ============================================
// PART 2: THE POST WITH A BODY
// ============================================
it("creates a user", () => {
cy.request("POST", "/api/users", {
name: "Alice", // the new record's name
email: "alice@example.com", // the new record's email
}).then((response) => {
expect(response.status).to.eq(201); // created
expect(response.body.id).to.be.a("number"); // the server assigned an id
expect(response.body.name).to.eq("Alice"); // the echo of the input
});
});
// ============================================
// PART 3: THE OPTIONS OBJECT
// ============================================
it("updates with custom headers", () => {
cy.request({
method: "PUT", // the update method
url: "/api/users/1", // the target record
body: { name: "Alice Updated" }, // the new values
headers: { "X-Trace-Id": "trace-1" }, // a correlation header
}).then((response) => {
expect(response.status).to.eq(200); // the update succeeded
expect(response.body.name).to.eq("Alice Updated");
});
});
// ============================================
// PART 4: THE ERROR PATH
// ============================================
it("returns 404 for a missing user", () => {
cy.request({
url: "/api/users/9999", // an id that does not exist
failOnStatusCode: false, // the 404 is expected
}).then((response) => {
expect(response.status).to.eq(404); // not found
expect(response.body.error).to.eq("Not Found");
});
});
// ============================================
// PART 5: THE LOGIN SHORTCUT
// ============================================
it("logs in through the API", () => {
cy.request("POST", "/api/login", {
username: "alice", // the test account
password: "secret", // the test password
}).then((response) => {
expect(response.status).to.eq(200); // the credentials are valid
// the session cookie is stored in the cookie jar automatically
});
});
// ============================================
// PART 6: THE BEARER TOKEN
// ============================================
it("uses a bearer token", () => {
cy.request({
url: "/api/profile", // the protected endpoint
auth: { bearer: Cypress.env("API_TOKEN") }, // the token from env
}).then((response) => {
expect(response.status).to.eq(200); // authorized
});
});
// ============================================
// PART 7: THE QUERY STRING
// ============================================
it("filters with query parameters", () => {
cy.request({
url: "/api/users", // the list endpoint
qs: { role: "admin", limit: 10 }, // the filter parameters
}).then((response) => {
expect(response.status).to.eq(200);
expect(response.body.length).to.be.at.most(10); // the limit applied
response.body.forEach((user) => {
expect(user.role).to.eq("admin"); // the filter applied
});
});
});
// ============================================
// PART 8: THE SEEDED UI TEST
// ============================================
it("shows a seeded record in the UI", () => {
cy.request("POST", "/api/users", {
name: "Seeded User", // the record the UI should show
email: "seeded@example.com",
}).then(() => {
cy.visit("/users"); // the list page
cy.contains("Seeded User").should("be.visible"); // the record is shown
});
});
// ============================================
// PART 9: THE CONTRACT ASSERTION
// ============================================
it("returns the full contract", () => {
cy.request("/api/users/1").then((response) => {
expect(response.body).to.have.keys( // the exact field set
"id", "name", "email", "createdAt"
);
expect(response.headers["content-type"])
.to.include("application/json"); // the response type
});
});
// ============================================
// PART 10: THE SESSION CACHE
// ============================================
beforeEach(() => {
cy.session("alice", () => {
cy.request("POST", "/api/login", {
username: "alice", // the cached login
password: "secret",
});
});
});
});
The ten parts covered the basic request, the POST with a body, the options object, the error path, the login shortcut, the bearer token, the query string, the seeded UI test, the contract assertion, and the cy.session cache.
Quick Reference
The Three Forms
| Form | Example | Default |
|---|---|---|
| URL string | cy.request("/api/users") | GET |
| Method and URL | cy.request("POST", "/api/users", body) | Explicit method |
| Options object | cy.request({ method, url, body, headers, qs }) | Fully explicit |
The Response Object
| Property | Type | Content |
|---|---|---|
status | number | The HTTP status code |
body | object | The parsed JSON body |
headers | object | The response headers |
duration | number | The request time in milliseconds |
Auth Options
| Option | Effect |
|---|---|
auth: { username, password } | HTTP Basic authentication |
auth: { bearer: token } | Bearer token in the header |
headers: { Authorization } | Any custom scheme |
cy.session() | Cache the login across tests |
Error and Control
| Option | Default | Effect |
|---|---|---|
failOnStatusCode | true | Fail on non-2xx |
failOnStatusCode: false | โ | Assert on error codes |
timeout | responseTimeout | Override the wait |
Best Practices
โ Do This:
// Seed data with cy.request, not the UI
cy.request("POST", "/api/users", user); // โ
// Assert on the full contract
expect(response.body).to.have.keys("id", "name", "email"); // โ
// Test the error path explicitly
cy.request({ url, failOnStatusCode: false }); // โ
// Cache the login with cy.session
cy.session("alice", () => { cy.request("POST", "/api/login", creds); }); // โ
// Use the options object for complex requests
cy.request({ method, url, body, headers, qs }); // โ
// Clean up the seeded data
cy.request("DELETE", `/api/users/${id}`); // โ
โ Don’t Do This:
// Create test data by clicking through the UI
cy.visit("/users/new"); cy.get("#name").type("Alice"); // โ
// Assert only the status
expect(response.status).to.eq(200); // โ
// Let the error path fail the test
cy.request("/api/users/9999"); // โ
// Log in through the UI in every test
cy.visit("/login"); cy.get("#user").type("alice"); // โ
// Leave seeded data behind
cy.request("POST", "/api/users", user); // no cleanup // โ
// Assume cy.request tests CORS
cy.request("/api"); // it bypasses CORS, it does not test it // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Test fails on 404 | failOnStatusCode defaults to true | Set failOnStatusCode: false |
| Cookie not stored | Different base URL or cookie domain | Match the baseUrl origin |
| CORS not caught | cy.request bypasses the browser | Test CORS with cy.intercept |
| Body not JSON | Wrong content-type header | Set content-type: application/json |
| Slow setup | Seeding through the UI | Seed with cy.request |
| Data leaks between tests | No cleanup after seeding | Delete the record in afterEach |
| Session not reused | No cy.session cache | Wrap the login in cy.session |
| Assertion on a string status | Comparing to "200" | Compare to the number 200 |
Real-World Examples
1. Health check
cy.request("/health").its("status").should("eq", 200);
2. List endpoint
cy.request("/api/users").its("body").should("be.an", "array");
3. Create a record
cy.request("POST", "/api/users", { name: "Alice" });
4. Update a record
cy.request("PUT", "/api/users/1", { name: "Alice Updated" });
5. Delete a record
cy.request("DELETE", "/api/users/1").its("status").should("eq", 204);
6. Bearer token
cy.request({ url: "/api/profile", auth: { bearer: token } });
7. Query filter
cy.request({ url: "/api/users", qs: { role: "admin" } });
8. Expected error
cy.request({ url: "/api/users/9999", failOnStatusCode: false });
9. Session cache
cy.session("alice", () => cy.request("POST", "/api/login", creds));
10. Seed then visit
cy.request("POST", "/api/users", user).then(() => cy.visit("/users"));
Visual
The Request Path
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CYPRESS TEST โ
โ โ
โ cy.request({ method, url, body }) โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ CYPRESS NODE PROCESS โ โ
โ โ (outside the browser) โ โ
โ โ โ โ
โ โ no CORS no interceptors โ โ
โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ โ
โ โ HTTP โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ BACKEND ENDPOINT โ โ
โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ โ
โ โ response โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ RESPONSE OBJECT โ โ
โ โ status body headers โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Three Forms
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FORM 1 cy.request(url) โ
โ GET by default โ
โ โ
โ FORM 2 cy.request(method, url, body) โ
โ explicit method โ
โ โ
โ FORM 3 cy.request({ method, url, body, headers, qs }) โ
โ full control โ
โ โ
โ ALL THREE YIELD THE SAME RESPONSE OBJECT โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Login Shortcut
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ BEFORE (UI LOGIN) AFTER (API LOGIN) โ
โ โ
โ cy.visit("/login") cy.request("POST", โ
โ cy.get("#user") "/api/login", creds) โ
โ cy.get("#pass") โ โ
โ cy.get("form").submit() โผ โ
โ cy.url().should(...) cookie stored in jar โ
โ โ โ โ
โ โผ โผ โ
โ cookie stored cy.visit("/dashboard") โ
โ โ already authenticated โ
โ โผ โ
โ cy.visit("/dashboard") โ
โ โ
โ ~5 UI steps ~1 request โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Seed and Assert
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SEED TEST CLEAN โ
โ โ
โ cy.request("POST", cy.visit("/users") cy. โ
โ "/api/users", โ requestโ
โ { name: "Temp" }) โผ ("DELETโ
โ โ cy.contains("Temp") E", โ
โ โผ .click() url) โ
โ response.body.id โ โ
โ (the seeded id) โผ โ
โ cy.contains("Temp") โ
โ .should("not.exist") โ
โ โ
โ the UI test starts from a known state, not a UI flow โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Command | cy.request |
| Execution context | Cypress Node process, not the browser |
| Default method | GET |
| Forms | URL, method+URL, options object |
| Response | status, body, headers, duration |
| Error control | failOnStatusCode |
| Auth | auth: { username, password } or { bearer } |
| Cookie storage | Automatic in the shared cookie jar |
| Session cache | cy.session() |
| CORS | Bypassed, not tested |
| Use for | Seeding, contract tests, login shortcut |
Key takeaways:
cy.requestruns in the Node process, not the browser. It bypasses CORS, does not trigger the app’s interceptors, and does not appear in the browser’s Network tab. It tests the endpoint, not the browser’s path to the endpoint.- The options object is the scalable form. The
method,url,body,headers, andqsproperties carry the whole request, and thefailOnStatusCode: falseoption lets the test assert on error codes explicitly. - The login shortcut is the most common use. Posting credentials to the login endpoint stores the session cookie in the shared jar, and the subsequent
cy.visitis already authenticated.cy.sessionis the modern way to cache that login across tests. - Seeding with
cy.requestisolates the UI test. The test creates its data in one request instead of a multi-step UI flow, so a failure in the creation flow does not fail the test that is about something else. - The contract assertion is the pure API test. Asserting on the full body shape catches a breaking backend change that a UI test would miss, because the UI might read only one field and ignore the rest.
Remember: cy.request is the bridge between the frontend test and the backend it depends on. Use it to seed state so UI tests start from a known record, to log in so UI tests skip the login flow, and to assert the API contract directly so a backend change is caught before it reaches the UI. It bypasses the browser’s network stack entirely, so it does not test CORS or interceptors, and that is exactly what makes it a clean, fast, and isolated way to test the endpoint itself.
Cypress cy.request, API testing, cy.session, failOnStatusCode, contract testing## Cypress 23 ๐ฒ API Testing โ cy.request and backend endpoint validation
Cypress is best known as a browser automation tool, but its cy.request command turns it into a capable API testing client as well. The command makes an HTTP request from the Cypress Node process, bypassing the browser’s security restrictions entirely, and yields the response object so that assertions can run against the status, headers, and body. This is the command that lets a single Cypress suite test both the frontend and the backend it talks to, without switching to a separate tool like Postman or a standalone HTTP client.
The important distinction is that cy.request is not a browser fetch. It runs outside the browser, so it is not subject to CORS, it does not trigger the application’s interceptors, and it does not appear in the Network tab of the browser’s DevTools. It is a direct HTTP call from the Node side of Cypress, and the response it yields is a plain object with status, body, headers, and duration properties. That makes it ideal for setting up state, validating endpoints, and testing the API layer independently of the UI.
This chapter covers the cy.request command in its three forms, the way it handles authentication and cookies, the pattern of using it to seed state before a UI test, and the assertions that run against the response. The sections that follow walk through the command signature, the request options, and the patterns that keep API tests reliable and independent.
Key point: cy.request makes an HTTP call from the Cypress Node process, not the browser, so it bypasses CORS, does not trigger the app’s interceptors, and yields a response object with status, body, headers, and duration that assertions can run against directly.
Why API testing inside Cypress exists
The frontend-backend gap problem. A UI test that clicks through a form and waits for a success message is testing the frontend, the backend, and the network between them all at once. When it fails, the failure could be in any of the three layers, and the debugging session starts by trying to figure out which one. A direct cy.request to the endpoint isolates the backend, and a UI test that uses cy.request to seed its data isolates the frontend. The gap between the two layers is where most flaky tests live, and cy.request is the tool that closes it.
The setup speed problem. A test that creates its data by clicking through the UI spends most of its time on the setup, not on the assertion. If the test is about a delete button, the five steps that create the record first are overhead. cy.request creates the record in a single call, and the UI test starts at the state it actually wants to verify. The setup becomes a single line instead of a multi-step flow, and the test runs faster and fails for the right reason.
The CORS problem. A browser fetch to a different origin is blocked by CORS unless the server sends the right headers, and a test that runs in the browser inherits that restriction. cy.request runs in the Node process, outside the browser’s security model, so it can call any endpoint the machine can reach. That is why it can hit a backend directly during a test even when the frontend’s origin is different.
The cookie and session problem. A login flow that goes through the UI takes a page load, a form fill, a submit, and a redirect. cy.request can post the credentials to the login endpoint and receive the session cookie directly, and Cypress stores that cookie in the browser’s cookie jar so the subsequent cy.visit is already authenticated. The login becomes one request instead of a UI flow.
The contract problem. The API’s response shape is a contract, and a test that only exercises it through the UI never checks the contract directly. The UI might read one field and ignore the rest, so a breaking change to a field the UI does not use goes undetected. A direct cy.request assertion on the body checks the whole contract, and the API test catches the break before the UI test does.
The trade-off. cy.request does not exercise the browser’s network stack, so it will not catch a CORS misconfiguration, a service worker interception, or a browser-level caching issue. It tests the endpoint, not the browser’s path to the endpoint. A suite that needs to verify the browser’s network behavior uses cy.intercept and a real page load, and cy.request is the complement for the endpoint itself.
a. The command signature and the three forms
cy.request has three forms. The first is a single URL string, which makes a GET by default. The second is a method and URL pair, which sets the HTTP method explicitly. The third is an options object, which carries the method, URL, body, headers, and query parameters together. All three yield the response object.
// Form 1: a plain URL, defaults to GET
cy.request("/api/users").then((response) => {
expect(response.status).to.eq(200); // the status is a number
});
// Form 2: method and URL
cy.request("POST", "/api/users", { name: "Alice" }).then((response) => {
expect(response.status).to.eq(201); // created
});
// Form 3: the options object
cy.request({
method: "PUT", // the HTTP method
url: "/api/users/1", // the endpoint
body: { name: "Alice Updated" }, // the JSON body, serialized automatically
headers: { "X-Trace-Id": "abc" }, // custom headers
qs: { expand: "roles" }, // query string parameters
}).then((response) => {
expect(response.body.name).to.eq("Alice Updated"); // the parsed JSON body
});
The options object is the form that scales. The body is serialized to JSON automatically when the content type is JSON, the qs object is appended to the URL as query parameters, and the headers object is merged into the request. The failOnStatusCode option, which defaults to true, decides whether a non-2xx status fails the test. Setting it to false lets the test assert on a 404 or a 500 explicitly.
// Assert on a 404 without the command failing the test
cy.request({
url: "/api/users/9999",
failOnStatusCode: false, // the 404 is expected, so do not fail
}).then((response) => {
expect(response.status).to.eq(404); // the endpoint returned not found
expect(response.body.error).to.eq("Not Found"); // the error body
});
The response object is the same for every form. The status is a number, the body is the parsed JSON when the response is JSON, the headers is an object of header names to values, and the duration is the request time in milliseconds. The requestHeaders and redirects properties are also present when they are relevant.
b. Authentication, cookies, and the session
The most common use of cy.request outside of pure API testing is the login shortcut. The test posts the credentials to the login endpoint, the server responds with a session cookie, and Cypress stores that cookie in the browser’s cookie jar. The next cy.visit is already authenticated, and the test skips the UI login flow entirely.
// Log in through the API and let Cypress store the session cookie
beforeEach(() => {
cy.request({
method: "POST",
url: "/api/login", // the login endpoint
body: { username: "alice", password: "secret" }, // the credentials
}).then((response) => {
expect(response.status).to.eq(200); // the login succeeded
// the Set-Cookie header is stored automatically in the cookie jar
});
});
it("shows the dashboard to a logged-in user", () => {
cy.visit("/dashboard"); // already authenticated
cy.contains("Welcome, Alice"); // the UI sees the session
});
The cookie storage is automatic for the default cypress.config setup, because cy.request and the browser share the same cookie jar. The cy.session command, introduced in Cypress 10, is the newer and more explicit way to cache the login across tests. It wraps the login logic and restores the cookies and localStorage for every test in the block, and it invalidates the cache when the session changes.
// The modern pattern: cache the login with cy.session
beforeEach(() => {
cy.session("alice", () => {
cy.request("POST", "/api/login", {
username: "alice",
password: "secret",
}).then((response) => {
expect(response.status).to.eq(200); // validated once, then cached
});
});
});
The auth option is the other way to send credentials. The auth: { username, password } object sends HTTP Basic authentication, and the auth: { bearer: token } form sends a Bearer token in the Authorization header. The headers option is the general escape hatch for any other scheme.
// Bearer token authentication
cy.request({
url: "/api/profile",
auth: { bearer: Cypress.env("API_TOKEN") }, // the token from the environment
}).then((response) => {
expect(response.status).to.eq(200); // authorized
});
c. Seeding state and asserting the contract
The pattern that makes UI tests reliable is to seed the data with cy.request and then verify the UI against the known state. The test does not click through the creation flow, so a failure in the creation flow does not fail the delete test, and the delete test starts from an exact record it created.
// Seed a record through the API, then test the UI against it
it("deletes a user from the list", () => {
cy.request("POST", "/api/users", {
name: "Temp User", // the record the test will delete
email: "temp@example.com",
}).then((response) => {
const userId = response.body.id; // the id the API assigned
cy.visit("/users"); // load the list page
cy.contains("Temp User") // the seeded record is visible
.parent() // the row container
.find("[data-cy=delete]") // the delete button in the row
.click(); // trigger the delete
cy.contains("Temp User").should("not.exist"); // gone from the list
cy.request(`/api/users/${userId}`).then((res) => {
expect(res.status).to.eq(404); // the backend actually deleted it
});
});
});
The contract assertion is the pure API test. It checks the status, the body shape, and the headers without touching the UI, and it is the test that catches a backend change before the frontend does. A suite of these covers the endpoints the app depends on, and they run fast because each one is a single request.
// A pure API contract test
it("returns the user with the expected shape", () => {
cy.request("/api/users/1").then((response) => {
expect(response.status).to.eq(200); // the happy path
expect(response.headers["content-type"]) // the content type
.to.include("application/json");
expect(response.body).to.have.keys( // the full contract
"id", "name", "email", "createdAt"
);
expect(response.body.id).to.be.a("number"); // the id is a number
expect(response.body.email).to.match(/@/); // the email looks valid
});
});
The cy.request chain is also the way to test an endpoint that the UI does not expose. A webhook receiver, an admin-only endpoint, or a health check is reachable with a single request, and the test verifies it without needing a page for it. The failOnStatusCode: false option is what lets the test assert on the error paths, which are the paths the UI rarely exercises.
Complete Example Session
// ============================================
// PART 1: THE BASIC REQUEST
// ============================================
describe("Users API", () => {
it("lists users", () => {
cy.request("/api/users").then((response) => {
expect(response.status).to.eq(200); // the list endpoint is healthy
expect(response.body).to.be.an("array"); // the body is an array
expect(response.body.length).to.be.greaterThan(0); // it has records
});
});
// ============================================
// PART 2: THE POST WITH A BODY
// ============================================
it("creates a user", () => {
cy.request("POST", "/api/users", {
name: "Alice", // the new record's name
email: "alice@example.com", // the new record's email
}).then((response) => {
expect(response.status).to.eq(201); // created
expect(response.body.id).to.be.a("number"); // the server assigned an id
expect(response.body.name).to.eq("Alice"); // the echo of the input
});
});
// ============================================
// PART 3: THE OPTIONS OBJECT
// ============================================
it("updates with custom headers", () => {
cy.request({
method: "PUT", // the update method
url: "/api/users/1", // the target record
body: { name: "Alice Updated" }, // the new values
headers: { "X-Trace-Id": "trace-1" }, // a correlation header
}).then((response) => {
expect(response.status).to.eq(200); // the update succeeded
expect(response.body.name).to.eq("Alice Updated");
});
});
// ============================================
// PART 4: THE ERROR PATH
// ============================================
it("returns 404 for a missing user", () => {
cy.request({
url: "/api/users/9999", // an id that does not exist
failOnStatusCode: false, // the 404 is expected
}).then((response) => {
expect(response.status).to.eq(404); // not found
expect(response.body.error).to.eq("Not Found");
});
});
// ============================================
// PART 5: THE LOGIN SHORTCUT
// ============================================
it("logs in through the API", () => {
cy.request("POST", "/api/login", {
username: "alice", // the test account
password: "secret", // the test password
}).then((response) => {
expect(response.status).to.eq(200); // the credentials are valid
// the session cookie is stored in the cookie jar automatically
});
});
// ============================================
// PART 6: THE BEARER TOKEN
// ============================================
it("uses a bearer token", () => {
cy.request({
url: "/api/profile", // the protected endpoint
auth: { bearer: Cypress.env("API_TOKEN") }, // the token from env
}).then((response) => {
expect(response.status).to.eq(200); // authorized
});
});
// ============================================
// PART 7: THE QUERY STRING
// ============================================
it("filters with query parameters", () => {
cy.request({
url: "/api/users", // the list endpoint
qs: { role: "admin", limit: 10 }, // the filter parameters
}).then((response) => {
expect(response.status).to.eq(200);
expect(response.body.length).to.be.at.most(10); // the limit applied
response.body.forEach((user) => {
expect(user.role).to.eq("admin"); // the filter applied
});
});
});
// ============================================
// PART 8: THE SEEDED UI TEST
// ============================================
it("shows a seeded record in the UI", () => {
cy.request("POST", "/api/users", {
name: "Seeded User", // the record the UI should show
email: "seeded@example.com",
}).then(() => {
cy.visit("/users"); // the list page
cy.contains("Seeded User").should("be.visible"); // the record is shown
});
});
// ============================================
// PART 9: THE CONTRACT ASSERTION
// ============================================
it("returns the full contract", () => {
cy.request("/api/users/1").then((response) => {
expect(response.body).to.have.keys( // the exact field set
"id", "name", "email", "createdAt"
);
expect(response.headers["content-type"])
.to.include("application/json"); // the response type
});
});
// ============================================
// PART 10: THE SESSION CACHE
// ============================================
beforeEach(() => {
cy.session("alice", () => {
cy.request("POST", "/api/login", {
username: "alice", // the cached login
password: "secret",
});
});
});
});
The ten parts covered the basic request, the POST with a body, the options object, the error path, the login shortcut, the bearer token, the query string, the seeded UI test, the contract assertion, and the cy.session cache.
Quick Reference
The Three Forms
| Form | Example | Default |
|---|---|---|
| URL string | cy.request("/api/users") | GET |
| Method and URL | cy.request("POST", "/api/users", body) | Explicit method |
| Options object | cy.request({ method, url, body, headers, qs }) | Fully explicit |
The Response Object
| Property | Type | Content |
|---|---|---|
status | number | The HTTP status code |
body | object | The parsed JSON body |
headers | object | The response headers |
duration | number | The request time in milliseconds |
Auth Options
| Option | Effect |
|---|---|
auth: { username, password } | HTTP Basic authentication |
auth: { bearer: token } | Bearer token in the header |
headers: { Authorization } | Any custom scheme |
cy.session() | Cache the login across tests |
Error and Control
| Option | Default | Effect |
|---|---|---|
failOnStatusCode | true | Fail on non-2xx |
failOnStatusCode: false | โ | Assert on error codes |
timeout | responseTimeout | Override the wait |
Best Practices
โ Do This:
// Seed data with cy.request, not the UI
cy.request("POST", "/api/users", user); // โ
// Assert on the full contract
expect(response.body).to.have.keys("id", "name", "email"); // โ
// Test the error path explicitly
cy.request({ url, failOnStatusCode: false }); // โ
// Cache the login with cy.session
cy.session("alice", () => { cy.request("POST", "/api/login", creds); }); // โ
// Use the options object for complex requests
cy.request({ method, url, body, headers, qs }); // โ
// Clean up the seeded data
cy.request("DELETE", `/api/users/${id}`); // โ
โ Don’t Do This:
// Create test data by clicking through the UI
cy.visit("/users/new"); cy.get("#name").type("Alice"); // โ
// Assert only the status
expect(response.status).to.eq(200); // โ
// Let the error path fail the test
cy.request("/api/users/9999"); // โ
// Log in through the UI in every test
cy.visit("/login"); cy.get("#user").type("alice"); // โ
// Leave seeded data behind
cy.request("POST", "/api/users", user); // no cleanup // โ
// Assume cy.request tests CORS
cy.request("/api"); // it bypasses CORS, it does not test it // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Test fails on 404 | failOnStatusCode defaults to true | Set failOnStatusCode: false |
| Cookie not stored | Different base URL or cookie domain | Match the baseUrl origin |
| CORS not caught | cy.request bypasses the browser | Test CORS with cy.intercept |
| Body not JSON | Wrong content-type header | Set content-type: application/json |
| Slow setup | Seeding through the UI | Seed with cy.request |
| Data leaks between tests | No cleanup after seeding | Delete the record in afterEach |
| Session not reused | No cy.session cache | Wrap the login in cy.session |
| Assertion on a string status | Comparing to "200" | Compare to the number 200 |
Real-World Examples
1. Health check
cy.request("/health").its("status").should("eq", 200);
2. List endpoint
cy.request("/api/users").its("body").should("be.an", "array");
3. Create a record
cy.request("POST", "/api/users", { name: "Alice" });
4. Update a record
cy.request("PUT", "/api/users/1", { name: "Alice Updated" });
5. Delete a record
cy.request("DELETE", "/api/users/1").its("status").should("eq", 204);
6. Bearer token
cy.request({ url: "/api/profile", auth: { bearer: token } });
7. Query filter
cy.request({ url: "/api/users", qs: { role: "admin" } });
8. Expected error
cy.request({ url: "/api/users/9999", failOnStatusCode: false });
9. Session cache
cy.session("alice", () => cy.request("POST", "/api/login", creds));
10. Seed then visit
cy.request("POST", "/api/users", user).then(() => cy.visit("/users"));
Visual
The Request Path
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CYPRESS TEST โ
โ โ
โ cy.request({ method, url, body }) โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ CYPRESS NODE PROCESS โ โ
โ โ (outside the browser) โ โ
โ โ โ โ
โ โ no CORS no interceptors โ โ
โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ โ
โ โ HTTP โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ BACKEND ENDPOINT โ โ
โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ โ
โ โ response โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ RESPONSE OBJECT โ โ
โ โ status body headers โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Three Forms
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FORM 1 cy.request(url) โ
โ GET by default โ
โ โ
โ FORM 2 cy.request(method, url, body) โ
โ explicit method โ
โ โ
โ FORM 3 cy.request({ method, url, body, headers, qs }) โ
โ full control โ
โ โ
โ ALL THREE YIELD THE SAME RESPONSE OBJECT โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Login Shortcut
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ BEFORE (UI LOGIN) AFTER (API LOGIN) โ
โ โ
โ cy.visit("/login") cy.request("POST", โ
โ cy.get("#user") "/api/login", creds) โ
โ cy.get("#pass") โ โ
โ cy.get("form").submit() โผ โ
โ cy.url().should(...) cookie stored in jar โ
โ โ โ โ
โ โผ โผ โ
โ cookie stored cy.visit("/dashboard") โ
โ โ already authenticated โ
โ โผ โ
โ cy.visit("/dashboard") โ
โ โ
โ ~5 UI steps ~1 request โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Seed and Assert
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SEED TEST CLEAN โ
โ โ
โ cy.request("POST", cy.visit("/users") cy. โ
โ "/api/users", โ requestโ
โ { name: "Temp" }) โผ ("DELETโ
โ โ cy.contains("Temp") E", โ
โ โผ .click() url) โ
โ response.body.id โ โ
โ (the seeded id) โผ โ
โ cy.contains("Temp") โ
โ .should("not.exist") โ
โ โ
โ the UI test starts from a known state, not a UI flow โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Command | cy.request |
| Execution context | Cypress Node process, not the browser |
| Default method | GET |
| Forms | URL, method+URL, options object |
| Response | status, body, headers, duration |
| Error control | failOnStatusCode |
| Auth | auth: { username, password } or { bearer } |
| Cookie storage | Automatic in the shared cookie jar |
| Session cache | cy.session() |
| CORS | Bypassed, not tested |
| Use for | Seeding, contract tests, login shortcut |
Key takeaways:
cy.requestruns in the Node process, not the browser. It bypasses CORS, does not trigger the app’s interceptors, and does not appear in the browser’s Network tab. It tests the endpoint, not the browser’s path to the endpoint.- The options object is the scalable form. The
method,url,body,headers, andqsproperties carry the whole request, and thefailOnStatusCode: falseoption lets the test assert on error codes explicitly. - The login shortcut is the most common use. Posting credentials to the login endpoint stores the session cookie in the shared jar, and the subsequent
cy.visitis already authenticated.cy.sessionis the modern way to cache that login across tests. - Seeding with
cy.requestisolates the UI test. The test creates its data in one request instead of a multi-step UI flow, so a failure in the creation flow does not fail the test that is about something else. - The contract assertion is the pure API test. Asserting on the full body shape catches a breaking backend change that a UI test would miss, because the UI might read only one field and ignore the rest.
Remember: cy.request is the bridge between the frontend test and the backend it depends on. Use it to seed state so UI tests start from a known record, to log in so UI tests skip the login flow, and to assert the API contract directly so a backend change is caught before it reaches the UI. It bypasses the browser’s network stack entirely, so it does not test CORS or interceptors, and that is exactly what makes it a clean, fast, and isolated way to test the endpoint itself.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!