Application Programming Interface, popularly called as APIs are an important aspect of software development lifecycle not only from the dev point of view but also from the testing perspective. These APIs facilitate interaction between different systems to exchange data. Hence, it becomes extremely important to test these APIs thoroughly to ensure seamless functioning of the application.
In this article we will explore API Testing with Cypress Testing Framework and see how we can automate our APIs for efficient testing. We will cover below points in this article-
Overview of API Testing
API testing involves sending the HTTP Request, be it the GET, POST, PUT, DELETE(or other methods) to the backend server and retrieving the responses. Once the responses are retrieved they are validated to ensure that the expected values have been received. Some key aspects of API testing are listed below
- Verifying the Status Code – Validation of the status code in the response is done to ensure that the desired status code is being received. For example, 200 status codes are expected to ensure Success. You can refer to other standard status codes used for HTTP Requests from the wiki documentation.
- Response Body Assertions – Validation of the HTTP response body to ensure that the XML or the JSON contains the expected data and has the correct structure.
- Testing the Request Parameter – Validation of the behaviour of API by passing different values in the parameters and the headers.
- Authentication & Authorization – Validation of proper authentication mechanism and security aspects. While testing the APIs, the above points are considered to ensure that the end-to-end functioning of API is bug free.
Utilising Cypress for API Testing
Cypress is a popular front-end testing tool, used for browser and end-to-end automation testing. Cypress comes with network request capabilities, which makes it a good choice for API testing as well. Some of the key features offered by Cypress for API Testing are-
- Familiarity in syntax – Similar to the UI tests, Cypress API commands use the same .should() and .then() syntax.
- Built-In Assertions – We can easily use the assertions provided by Cypress to assert the status code, or headers or even the response body of API requests.
- Retrying failed requests – Cypress automatically retries the failed requests to ensure that there is no network or other similar issue.
Elaborate Documentation – Cypress has nicely documented requests and assertions making it easy to get support on the run.
Key Features of Cypress API Testing
Cypress comes with a variety of features to help you perform API Testing effectively and efficientl. A few features are discussed below-
- cy.wait() – Provides a mechanism to wait for a network request, and helps load asynchronous data.
- cy.route() – Helps to route test requests to specific handlers.
- cy.server() – helps to maintain an entire server for a test suite.
- Test Runners – Help in parallel execution of tests for quick turnaround time.
- cy.login() – Helps in making secured API requests by setting authorization headers with a single command before the calls.
- cy.intercept() – Controls the responses, or simulates the behaviour by intercepting the requests. With these features it becomes very easy and convenient for the user to start writing the API tests with enhanced capabilities and efficient framework.
Now that we understand how Cypress can help in automating our APIs let us write a simple API Test using Cypress. But before that you need to ensure that below prerequisites are fulfilled-
- Install an IDE like Visual Studio (this is the most used IDE, but you may refer some other IDE like IntelliJ as well)
- Install Node.js in your system Let us now walk through the steps of writing our first API test using Cypress.
Writing the First API Test using Cypress
In this article we will cover a simple scenario of sending HTTP Requests using the GET, POST, PUT, and DELETE methods. But before we start writing the test script we will set up the environment.
- Create a folder locally in your system, I have created a folder called CypressAPITests in my system.
cypress api
2 . Next, open the Visual Studio Code editor and open the folder as created in Step#1.
3 . Now that you have opened the folder, the next step is to set up the node project. To do so, in the terminal use the command npm init -y, this will create a package.json file.
4 . We will now install Cypress from the terminal, if not already done, using the command npx cypress install.
5 . We will now create the configuration files for our test, and to do so, we will run the command npx cypress open in the terminal.
6 . Once the Cypress tool opens up, select E2E Testing.
7 . Click on Continue on the next screen.
8 . Once the configuration files have been set up, go back to the Visual Studio Code editor and you will see a config file has been created.
9 . Now Cypress has been installed successfully and also the environment is all set. We will begin writing our tests now.
We will be using some dummy API calls to demo the Cypress API Automation.
In the Visual Studio Code editor, create a folder e2e under the Cypress directory. Under the e2e folder you can create another folder by the name of APITests. Note that you may select the folder name as per your requirement.
Now we will start writing our first test file. We will create a file under the APITests folder. Let us name it as HttpGetRequest. This file name will have an extension of .cy.js as shown in the snapshot below-
Now we will start writing the main code. Before doing that let us look at the basic syntax of the request-
cy.request(METHOD,url,body)
In the request made using Cypress, the url is a mandatory parameter but other parameters like Method and body are optional. You may look at the different request syntax from the official documentation of Cypress to get more understanding on how we can use it differently.
In our example scenario, we will be using the GET method to fetch some resources, so we will use the Method and the url as the parameters to cy.request.
cy.request('GET','https://dummy.restapiexample.com/api/v1/employees')
This command will make the API call to the server.
Next, we will assert some response value, for example the status code.
.its('status')
.should('equal',200);
This line of code will validate the response status code and assert that its value is 200.
Let us look at how this code will look once it is brought together:
describe('HTTPGet',()=>{
it('GET request',()=>{
cy.request('GET','https://dummy.restapiexample.com/api/v1/employees')
.its('status')
.should('equal',200);
})
})
After writing the code for a GET request we will execute the same. To execute it, we can use any of the two ways-
- Execution through terminal
- Execution through Cypress tool We will see one by one how we can perform the execution.
Execution through Terminal
To execute the Cypress code through terminal, open the terminal window and simply pass the command:
npx cypress run –spec “filepath”
In the above command the file path is the relative path of the file you would want to execute. Below snapshot shows the execution of HTTPGetRequest file on my system-
You can see that the test execution was successful and our API test has passed.
Let us now try executing the same test through the Cypress Tool.
Execution through Cypress Tool
1 . Simply write the command npx cypress open to open the tool.
- Once you see the tool window opened up, click on E2E Testing.
- Now select any browser. I am selecting Electron.
- You will see that the Electron browser opens up with the specs that we have written the Visual Studio Code being displayed.
- Select the HttpGetRequest and you will see that the execution begins with logs being displayed.
And there you have executed your first Cypress API Automation Test. We will now enhance our code to execute a couple of other HTTP Methods.
POST Method
Code to execute the POST HTTP Request-
describe('HTTPGet',()=>{
it('POST request',()=>{
cy.request({
method: 'POST',
url: 'https://dummy.restapiexample.com/api/v1/create',
body: {
"name":"test post",
"salary":"1234",
"age":"23"
}
})
.its('status')
.should('equal',200);
})
})
Upon, executing the above code the logs will be displaying the execution results as shown below-
For our next demonstrations we will use another fake API collection and see how the HTTP request methods work for them.
PUT Method
Code to execute the PUT HTTP Request-
describe('HTTPPut',()=>{
it('PUT request',()=>{
cy.request({
method: 'PUT',
url: 'https://jsonplaceholder.typicode.com/posts/1',
body: {
id: 1,
title: 'This is PUT Update',
body: 'This is PUT Update body',
userId: 1,
}
})
.its('status')
.should('equal',200) ;
})
})
Execution result of the above code are displayed below-
DELETE Method
Code to execute the Delete HTTP Request(Note that I appended the below piece of code in the same example I used above)-
it('DELETE request',()=>{
cy.request({
method: 'DELETE',
url: 'https://jsonplaceholder.typicode.com/posts/1',
})
.its('status')
.should('equal',200) ;
})
Since both PUT and DELETE request were in the same file, both the methods got executed and the results are as displayed below-
So, this is it and you now know how you can execute the basic HTTP Requests for different Methods using Cypress. You may now go ahead and try to implement Cypress API Testing in your projects and see how easily you are able to test the APIs with quick turnaround times.
Conclusion
After having gone through the basics of API and Cypress for API Testing we with conclude on below points-
- Cypress API Testing helps with a powerful set of tools which provides familiarity to Cypress’ syntax for UI Tests.
- We can use assertions conveniently to validate the response status code and any other response parameter.
Source: This article was originally published at testgrid.io.
The above is the detailed content of Mastering Cypress API Testing: A Comprehensive Guide with Examples. For more information, please follow other related articles on the PHP Chinese website!

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools
