How to Use cy.request in Cypress for API Testing
Use
cy.request in Cypress to send HTTP requests like GET, POST, PUT, or DELETE directly from your tests without visiting a page. It helps test APIs by making requests and asserting responses easily with simple syntax.Syntax
The cy.request command sends an HTTP request. You can specify the method, URL, headers, body, and other options.
Basic syntax:
method: HTTP method like GET, POST, PUT, DELETE (default is GET)url: The endpoint URL to requestbody: Data to send with POST or PUT requestsheaders: Optional HTTP headersfailOnStatusCode: Set to false to prevent test failure on error status codes
javascript
cy.request({
method: 'GET',
url: '/api/users',
headers: { 'Authorization': 'Bearer token' },
failOnStatusCode: false
}).then((response) => {
// assertions here
})Example
This example shows how to send a POST request to create a user and check the response status and body.
javascript
describe('API Test with cy.request', () => { it('creates a new user and verifies response', () => { cy.request({ method: 'POST', url: 'https://jsonplaceholder.typicode.com/users', body: { name: 'John Doe', email: 'john@example.com' } }).then((response) => { expect(response.status).to.equal(201) expect(response.body).to.have.property('name', 'John Doe') expect(response.body).to.have.property('email', 'john@example.com') }) }) })
Output
Test passes if response status is 201 and body contains the sent user data.
Common Pitfalls
Common mistakes when using cy.request include:
- Not handling asynchronous nature properly by missing
thenfor assertions. - Forgetting to set
failOnStatusCode: falsewhen testing error responses, causing tests to fail unexpectedly. - Using relative URLs without setting
baseUrlin Cypress config, leading to request failures. - Sending incorrect request body format (e.g., forgetting to stringify JSON if needed).
javascript
/* Wrong: Missing then for assertions */ cy.request('GET', '/api/data') expect(true).to.be.true // This runs before request finishes /* Right: Use then to wait for response */ cy.request('GET', '/api/data').then((response) => { expect(response.status).to.equal(200) })
Quick Reference
| Option | Description | Default |
|---|---|---|
| method | HTTP method (GET, POST, etc.) | GET |
| url | Request URL or path | Required |
| body | Data sent with POST/PUT requests | null |
| headers | HTTP headers object | {} |
| failOnStatusCode | Do not fail test on error status | true |
| timeout | Request timeout in ms | default Cypress timeout |
Key Takeaways
Use cy.request to send HTTP requests directly in Cypress tests without UI interaction.
Always use .then() to handle the asynchronous response and make assertions.
Set failOnStatusCode to false when testing expected error responses to avoid test failures.
Use full URLs or configure baseUrl in Cypress config for relative paths.
Check response status and body to verify API behavior accurately.