request | Cypress Documentation (2024)

Make an HTTP request.

Syntax

cy.request(url)
cy.request(url, body)
cy.request(method, url)
cy.request(method, url, body)
cy.request(options)

Usage

Correct Usage

cy.request('http://dev.local/seed')

Arguments

url (String)

The URL to make the request to.

If you do not provide a fully qualified domain name (FQDN) URL, Cypress willmake its best guess as to which host you want cy.request() to use in the URL.

  1. If you make a cy.request() after visiting a page, Cypress assumes the URLused for the cy.visit() is the host.
cy.visit('http://localhost:8080/app')
cy.request('users/1.json') // URL is http://localhost:8080/users/1.json
  1. If you make a cy.request() prior to visiting a page, Cypress assumes thehost is the baseUrl property configured inside of of yourconfiguration file.
  • cypress.config.js
  • cypress.config.ts
const { defineConfig } = require('cypress')

module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:1234',
},
})
cy.request('seed/admin') // URL is http://localhost:1234/seed/admin
  1. If Cypress cannot determine the host it will throw an error.

body (String, Object)

A request body to be sent in the request. Cypress sets the Accepts requestheader and serializes the response body by the encoding option.

method (String)

Make a request using a specific method. If no method is defined, Cypress usesthe GET method by default.

Supported methods include:

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH
  • HEAD
  • OPTIONS
  • TRACE
  • COPY
  • LOCK
  • MKCOL
  • MOVE
  • PURGE
  • PROPFIND
  • PROPPATCH
  • UNLOCK
  • REPORT
  • MKACTIVITY
  • CHECKOUT
  • MERGE
  • M-SEARCH
  • NOTIFY
  • SUBSCRIBE
  • UNSUBSCRIBE
  • SEARCH
  • CONNECT

options (Object)

Pass in an options object to change the default behavior of cy.request().

You can also set options for cy.request()'s baseUrl and responseTimeoutglobally in configuration.

OptionDefaultDescription
logtrueDisplays the command in the Command log
urlnullThe URL to make the request to
methodGETThe HTTP method to use in the request
authnullAdds Authorization headers. Accepts these options.
bodynullBody to send along with the request
failOnStatusCodetrueWhether to fail on response codes other than 2xx and 3xx
followRedirecttrueWhether to automatically follow redirects
formfalseWhether to convert the body values to URL encoded content and set the x-www-form-urlencoded header
encodingutf8The encoding to be used when serializing the response body. The following encodings are supported: ascii, base64, binary, hex, latin1, utf8, utf-8, ucs2, ucs-2, utf16le, utf-16le
gziptrueWhether to accept the gzip encoding
headersnullAdditional headers to send; Accepts object literal. Note: headers will only be sent for the initial request for cy.request(), not for any subsequent requests.
qsnullQuery parameters to append to the url of the request
retryOnStatusCodeFailurefalseWhether Cypress should automatically retry status code errors under the hood. Cypress will retry a request up to 4 times if this is set to true.
retryOnNetworkFailuretrueWhether Cypress should automatically retry transient network errors under the hood. Cypress will retry a request up to 4 times if this is set to true.
timeoutresponseTimeoutTime to wait for cy.request() to resolve before timing out

You can also set options for cy.request()'s baseUrl and responseTimeoutglobally in the Cypress configuration.

Yields

cy.request() yields the response as an object literal containing propertiessuch as:

  • status
  • body
  • headers
  • duration

Examples

URL

Make a GET request

cy.request() is great for talking to an external endpoint before your tests toseed a database.

beforeEach(() => {
cy.request('http://localhost:8080/db/seed')
})

Issue an HTTP request

Sometimes it's quicker to test the contents of a page rather thancy.visit() and wait for the entire page and all of itsresources to load.

cy.request('/admin').its('body').should('include', '<h1>Admin</h1>')

Method and URL

Send a DELETE request

cy.request('DELETE', 'http://localhost:8888/users/827')

Alias the request using .as()

cy.request('https://jsonplaceholder.cypress.io/comments').as('comments')

cy.get('@comments').should((response) => {
expect(response.body).to.have.length(500)
expect(response).to.have.property('headers')
expect(response).to.have.property('duration')
})

Method, URL, and Body

Send a POST request with a JSON body

cy.request('POST', 'http://localhost:8888/users/admin', { name: 'Jane' }).then(
(response) => {
// response.body is automatically serialized into JSON
expect(response.body).to.have.property('name', 'Jane') // true
}
)

Options

Request a page while disabling auto redirect

To test the redirection behavior of a login without a session, cy.request canbe used to check the status and redirectedToUrl property.

The redirectedToUrl property is a special Cypress property that normalizes theURL the browser would normally follow during a redirect.

cy.request({
url: '/dashboard',
followRedirect: false, // turn off following redirects
}).then((resp) => {
// redirect status code is 302
expect(resp.status).to.eq(302)
expect(resp.redirectedToUrl).to.eq('http://localhost:8082/unauthorized')
})

Download a PDF file

By passing the encoding: binary option, the response.body will be serializedbinary content of the file. You can use this to access various file types via.request() like .pdf, .zip, or .doc files.

cy.request({
url: 'http://localhost:8080/some-document.pdf',
encoding: 'binary',
}).then((response) => {
cy.writeFile('path/to/save/document.pdf', response.body, 'binary')
})

Get Data URL of an image

By passing the encoding: base64 option, the response.body will bebase64-encoded content of the image. You can use this to construct aData URIfor use elsewhere.

cy.request({
url: 'https://docs.cypress.io/img/logo.png',
encoding: 'base64',
}).then((response) => {
const base64Content = response.body
const mime = response.headers['content-type'] // or 'image/png'
// see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
const imageDataUrl = `data:${mime};base64,${base64Content}`
})

HTML form submissions using form option

Oftentimes, once you have a proper e2e test around logging in, there's no reasonto continue to cy.visit() the login and wait for the entire page to load allassociated resources before running any other commands. Doing so can slow downour entire test suite.

Using cy.request(), we can bypass all of this because it automatically getsand sets cookies as if the requests had come from the browser.

cy.request({
method: 'POST',
url: '/login_with_form', // baseUrl is prepend to URL
form: true, // indicates the body should be form urlencoded and sets Content-Type: application/x-www-form-urlencoded headers
body: {
username: 'jane.lane',
password: 'password123',
},
})

// to prove we have a session
cy.getCookie('cypress-session-cookie').should('exist')

Using cy.request() for HTML Forms

info

Check out our example recipe using cy.request() for HTML web forms

Request Polling

Call cy.request() over and over again

This is useful when you're polling a server for a response that may take awhileto complete.

All we're really doing here is creating a recursive function. Nothing morecomplicated than that.

// a regular ol' function folks
function req () {
cy
.request(...)
.then((resp) => {
// if we got what we wanted

if (resp.status === 200 && resp.body.ok === true)
// break out of the recursive loop
return

// else recurse
req()
})
}

cy
// do the thing causing the side effect
.get('button').click()

// now start the requests
.then(req)

Notes

Debugging

Request is not displayed in the Network Tab of Developer Tools

Cypress does not actually make an XHR request from the browser. We areactually making the HTTP request from Cypress (in Node). So, you won't see therequest inside of your Developer Tools.

CORS

CORS is bypassed

Normally when the browser detects a cross-origin HTTP request, it will send anOPTIONS preflight check to ensure the server allows cross-origin requests, butcy.request() bypasses CORS entirely.

// we can make requests to any external server, no problem.
cy.request('https://www.google.com/webhp?#q=cypress.io+cors')
.its('body')
.should('include', 'Testing, the way it should be') // true

Cookies

Cookies are automatically sent and received

Before sending the HTTP request, we automatically attach cookies that would haveotherwise been attached had the request come from the browser. Additionally, ifa response has a Set-Cookie header, these are automatically set back on thebrowser cookies.

In other words, cy.request() transparently performs all of the underlyingfunctions as if it came from the browser.

cy.intercept()

cy.request() sends requests to actual endpoints, bypassing those defined using cy.intercept()

The intention of cy.request() is to be used for checking endpoints on anactual, running server without having to start the front end application.

User agent

Trying to change the User-Agent?

Seehow to override the browser's default user agent.

Rules

Requirements

  • cy.request() requires being chained off of cy.
  • cy.request() requires that the server sends a response.
  • cy.request() requires that the response status code be 2xx or 3xx whenfailOnStatusCode is true.

Assertions

  • cy.request() will only run assertions you have chained once, and will notretry.

Timeouts

  • cy.request() can time out waiting for the server to respond.

Command Log

Request comments endpoint and test response

cy.request('https://jsonplaceholder.typicode.com/comments').then((response) => {
expect(response.status).to.eq(200)
expect(response.body).to.have.length(500)
expect(response).to.have.property('headers')
expect(response).to.have.property('duration')
})

The commands above will display in the Command Log as:

request | Cypress Documentation (1)

When clicking on request within the command log, the console outputs thefollowing:

request | Cypress Documentation (2)

History

VersionChanges
4.7.0Added support for encoding option.
3.3.0Added support for options retryOnStatusCodeFailure and retryOnNetworkFailure.
3.2.0Added support for any valid HTTP method argument including TRACE, COPY, LOCK, MKCOL, MOVE, PURGE, PROPFIND, PROPPATCH, UNLOCK, REPORT, MKACTIVITY, CHECKOUT, MERGE, M-SEARCH, NOTIFY, SUBSCRIBE, UNSUBSCRIBE, SEARCH, and CONNECT.

See also

  • cy.exec()
  • cy.task()
  • cy.visit()
  • Recipe: Logging In - Single Sign on
  • Recipe: Logging In - HTML Web Form
  • Recipe: Logging In - XHR Web Form
  • Recipe: Logging In - CSRF Tokens
request | Cypress Documentation (2024)

FAQs

How to failOnStatusCode false? ›

By using the { failOnStatusCode: false } option in cy. visit, you can just modify the test case not to fail when the application returns a status code other than 2xx and 3xx. You can handle unexpected status codes when calling any API as well.

How does Cypress wait until request is finished? ›

Using an Array of Aliases​

wait() , Cypress will wait for all requests to complete within the given requestTimeout and responseTimeout .

How to pass an authorization header in Cypress? ›

Step 1: Authorization Tab, and then enter a username and password. Press the “Send” button. Step 2: If it returns a '200' status as a response, Click on the 'Headers' tab, and copy the value of the 'Authorization' header, which is the required token id.

What is the difference between CY request and CY API? ›

api() work almost similar to cy. request() the main difference is that in cy. api() in addition to calling your API, it will print our information about the API call in your Cypress runner.

What is the status code 3XX? ›

3xx redirection

This class of status code indicates the client must take additional action to complete the request. Many of these status codes are used in URL redirection.

What is the difference between Cy visit and Cy intercept? ›

cy. visit() will resolve once its load event fires. The cy. intercept() command is not processed until after cy.

How do I make Cypress tests faster? ›

Tips To Improve Cypress Testing
  1. Set a baseUrl: ...
  2. Use aliases in cy. ...
  3. Avoid visiting external sites while test execution. ...
  4. Avoid coupling of tests. ...
  5. Using hooks the right way. ...
  6. Incorporate Cypress into your Continuous Integration and cloud testing plan.
May 3, 2023

What to use instead of cy wait? ›

Instead of relying on cy. wait(TIME) , it's better to use cy. get() with assertions that automatically retry until the presence of specific DOM elements signals the page has loaded. These assertions can be chained to keep retrying until certain conditions are met.

How to avoid waits in Cypress? ›

The best way to handle these waits is to wait on aliases. Anything that can be aliased can be waited upon, like elements, intercepts, requests, etc. Let's take a look at an example of what this looks like in practice. describe("User Sign-up and Login", () => { beforeEach(() => { cy.

How to handle SSO in Cypress? ›

Enable SSO​
  1. Log in to Cypress Cloud and navigate to the Integrations page for your organization.
  2. Scroll down to the Enterprise SSO section. Select your SSO provider and take note of the information provided and required.
Jan 16, 2024

What is cy intercept and cy route? ›

cy. intercept can be used solely for spying: to passively listen for matching routes and apply aliases to them without manipulating the request or its response in any way. This alone is powerful as it allows you to wait for these requests, resulting in more reliable tests.

How to hit API in Cypress? ›

To make an API request, Cypress automation provides an inbuilt command called cy. request(). With this command, Cypress will make an HTTP request on behalf of the web application and get the response from the API server. When the API request is successful, we will get the response status as 2xx.

How to handle cookies in Cypress? ›

Cookies
  1. getCookie() To get a browser cookie, use the cy. ...
  2. getCookies() To get browser cookies for the current domain, use the cy. ...
  3. getAllCookies() To get all browser cookies, use the cy. ...
  4. setCookie() To set a browser cookie, use the cy. ...
  5. clearCookie() To clear a browser cookie, use the cy. ...
  6. clearCookies() ...
  7. clearAllCookies()

What is the difference between @RequestParam and request body? ›

@RequestBody is used to extract the HTTP request body data, often in JSON or XML format, and deserialize it into a Java object. @RequestParam is used to extract individual parameter values from the request URL or submitted form data.

Is Cy get asynchronous? ›

Cypress commands do not return their subjects, they yield them. Remember: Cypress commands are asynchronous and get queued for execution at a later time.

Can Cypress do something if test fails? ›

With test retries, Cypress is able to retry failed tests to help detect test flakiness and continuous integration (CI) build failures. By doing so, this will save your team valuable time and resources so you can focus on what matters most to you.

How to handle timeout error in Cypress? ›

Command Timeout (defaultCommandTimeout): This timeout controls how long Cypress will wait for a single command to complete. A command that takes longer than this timeout will result in a timeout error. You can configure this timeout in your Cypress configuration file (cypress. json) or using Cypress.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Sen. Emmett Berge

Last Updated:

Views: 5945

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.