Cypress · Browser testing end to end
How do you test APIs with cy.request?
Short answer
cy.request sends an HTTP request from Node and yields the response without involving the UI. Use it to test API contracts, seed data, and log in, then assert on status, headers and body.
cy.request is a first-class HTTP client inside Cypress. It does not need a visited page, it does not go through the browser's XHR, and it yields the response for assertions. That makes it useful both for API tests and for setup in UI tests, such as creating a user or authenticating.
describe("orders api", () => {
it("creates an order", () => {
cy.request({
method: "POST",
url: "/api/orders",
body: { items: [{ sku: "desk-lamp", quantity: 2 }] },
headers: { "content-type": "application/json" },
}).then((response) => {
expect(response.status).to.eq(201);
expect(response.body).to.have.property("id");
expect(response.body.items).to.have.length(1);
});
});
});What cy.request is good for
- Contract checks for status, headers and response shape
- Seeding data before a UI test through the real API
- Logging in and reusing the cookie for a UI test
- Checking that a mutation returns the expected resource
- Failing fast when a backend dependency is broken
cy.request does not validate the browser's handling of a response. A UI test still matters for rendering, client validation and error presentation. Use both: request tests for the contract, browser tests for the user journey.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How is cy.request different from a browser fetch?
- 2How can cy.request help with authentication?
- 3What does cy.request yield?
- 4When would you use a separate API test suite?
Say it in the interview
cy.request sends HTTP directly from Node and yields the response. I use it to test API contracts and to set up state such as a user or a session before a UI test. I assert on status, headers and body in a then callback. It does not exercise rendering, so for user-facing flows I still keep browser tests alongside the request tests.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Cypress mock interview and get scored feedback on depth, clarity and confidence.