top of page

Test Data with API for Cypress Test


UI flows are great for end-to-end confidence, but they’re slow when used just to “prepare data”. A common Cypress pattern is:

  • create the test data via API

  • run the real scenario via UI

  • validate the result in the UI (and optionally via API)


This page is a reference for that workflow.


Why cy.request() is Useful


cy.request() sends HTTP calls directly to the backend. It’s perfect for:

  • creating articles/users/orders fast

  • avoiding flaky UI setup steps

  • keeping tests focused on the thing they actually want to validate


The object-based syntax is easiest to maintain:

Authentication: Log In and Extract the Token


The login request returns a response body with a token. Best practice is:

  • assert status code first

  • then extract the token from response.body

  • build the Authorization header: "Token " + token


Important detail: the token lives inside the .then() scope, so the next request should be chained inside it.

Create an Article via API (Fast Setup)


Once the token is available, create an article using the API:

  • method: POST

  • url: /api/articles

  • header: Authorization: token

  • body: article payload


Validate:

  • 201 status code (created)

  • title matches what was sent


Combine API Setup with UI Validation


This is the main value: create data quickly via API, then use the UI for the actual test action.


Example goal:

  • create article via API

  • delete article via UI

  • verify it disappears from the list


Reliable Timing: Add cy.intercept() + cy.wait()


After clicking Delete Article, the UI usually refreshes the article list by calling the articles API.

Without waiting, a test can fail by checking the list too early.


Solution:

  • intercept the articles call

  • wait for it after delete

  • then assert


Full Example: Create via API, Delete via UI

Best Practices Checklist


  • Assert status codes before using response data (200, 201, etc.)

  • Use response.body to read JSON

  • Chain requests inside .then() when variables (token) are needed

  • Use cy.intercept() + cy.wait() to avoid false failures after UI actions

  • Consider cleanup after tests (delete test data via API if needed)

 
 
bottom of page