Cypress API Testing
In today's interconnected digital landscape, APIs (Application Programming Interfaces) play a crucial role in enabling seamless communication between different software applications. Whether it's a web service, a system interface, or a library, APIs are the backbone of most modern applications, allowing the frontend and backend systems to interact efficiently.
Given the critical importance of APIs, ensuring their reliability, performance, and security is essential. This is where API testing comes into play. API testing involves directly testing the APIs to verify that they function as expected under various conditions. It helps identify issues early in the development process, ensuring that the APIs meet the required standards before they are deployed to production.
Table of Content
What is an API?
An API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other. APIs define methods and data structures that developers can use to interact with the software, whether it's a web service, a library, or a system interface.
Purpose of API Testing
API testing involves testing the APIs directly to ensure they work as expected. This is crucial because APIs are the backbone of most modern applications, enabling the interaction between the frontend and backend systems. API testing helps ensure the reliability, performance, and security of these interactions.
Here's a step-by-step guide to executing the Cypress API testing article using Visual Studio with the command prompt as the terminal.
Setting up the Environment
Step 1: Install Node.js and npm
First, you need to ensure that Node.js and npm are installed. You can check this by running the following commands in the terminal:
node -v
npm -v
If Node.js is not installed, download and install it from official document from npm. This will also install npm.

Step 2: Create a New Project Directory
- Open Visual Studio.
- Open the terminal by navigating to View > Terminal.
- In the terminal, create a new directory for your project and navigate into it
mkdir Cypress-Api-Testing
cd Cypress-Api-Testing
Step 3: Initialize a New Node.js Project
Run the following command to initialize a new Node.js project
npm init -y
This will create a package.json file in your project directory.

Step 4: Install Cypress
Now, install Cypress as a development dependency by running:
npm install cypress --save-dev

Step 5: Open Cypress
Once installed, open Cypress to create the default directory structure:
npx cypress open
This will create a cypress folder with subdirectories like integration, fixtures, and support.


Writing and Executing Your First Cypress API Test
Step 1: Create a Test File
Inside the cypress/e2e folder, create a new test file called api_test_spec.js. You can do this using the terminal:
cypress/e2e/api_test_spec.js
Step 2: Write Your First Test
Open the api_test_spec.js file in Visual Studio and write the following test code:
describe("API Testing with Cypress", () => {
it("GET request - validate status code", () => {
cy.request(
"https://jsonplaceholder.typicode.com/posts/1")
.its("status")
.should("equal", 200);
});
});

This test sends a GET request to a sample API and checks that the response status code is 200.
Step 3: Run the Test
Save the file and run the test in the Cypress Test Runner that opened when you ran npx cypress open.
If Cypress is not open, you can run it again using:
npx cypress open
Click on the api_test_spec.js test file in the Cypress Test Runner to execute the test. You should see the test run successfully.
Syntax
Making HTTP Requests with Cypress
Cypress makes it easy to work with different HTTP methods. Here’s how you can perform basic operations:
GET Request:
cy.request("GET",
"https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
expect(response.status).to.eq(200);
expect(response.body).to.have.property("id", 1);
});
POST Request:
cy.request("POST",
"https://jsonplaceholder.typicode.com/posts",
{title : "foo", body : "bar", userId : 1})
.then((response) => {
expect(response.status).to.eq(201);
expect(response.body)
.to.have.property("title", "foo");
});
PUT Request:
cy.request(
"PUT", "https://jsonplaceholder.typicode.com/posts/1",
{id : 1, title : "foo", body : "bar", userId : 1})
.then((response) => {
expect(response.status).to.eq(200);
expect(response.body)
.to.have.property("title", "foo");
});
DELETE Request:
cy.request("DELETE",
"https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
expect(response.status).to.eq(200);
});
All the requests:
describe('API Testing with Cypress', () => {
it('GET request - validate status code', () => {
cy.request('https://jsonplaceholder.typicode.com/posts/1')
.its('status')
.should('equal', 200);
});
it('POST request - create a new post', () => {
cy.request('POST', 'https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
}).then((response) => {
expect(response.status).to.eq(201);
expect(response.body).to.have.property('title', 'foo');
});
});
it('PUT request - update a post', () => {
cy.request('PUT', 'https://jsonplaceholder.typicode.com/posts/1', {
id: 1,
title: 'baz',
body: 'qux',
userId: 1
}).then((response) => {
expect(response.status).to.eq(200);
expect(response.body).to.have.property('title', 'baz');
});
});
it('DELETE request - delete a post', () => {
cy.request('DELETE', 'https://jsonplaceholder.typicode.com/posts/1')
.then((response) => {
expect(response.status).to.eq(200);
});
});
});

Assertions in Cypress API Testing
Types of Assertions
Assertions are used to verify that the application under test behaves as expected. In Cypress, you can use built-in assertions to validate API responses:
Status Code:
cy.request("https://jsonplaceholder.typicode.com/posts/1")
.its("status")
.should("equal", 200);
Response Body:
cy.request("https://jsonplaceholder.typicode.com/posts/1")
.its("body")
.should("include", {id : 1});
Headers:
cy.request("https://jsonplaceholder.typicode.com/posts/1")
.its("headers")
.its("content-type")
.should("include", "application/json");
Advanced Cypress API Testing
Handling Authentication
APIs often require authentication. You can handle this in Cypress by including headers in your requests:
cy.request({
method : "POST",
url : "https://api.example.com/authenticate",
body : {username : "user", password : "pass"}
}).then((response) => {
const token = response.body.token;
cy.request({
method : "GET",
url : "https://api.example.com/protected",
headers : {Authorization : `Bearer ${token}`}
})
.then(
(resp) => { expect(resp.status).to.eq(200); });
});
Chaining Requests
You can chain requests together in Cypress to validate a sequence of API calls:
cy.request("POST",
"https://jsonplaceholder.typicode.com/posts",
{title : "foo", body : "bar", userId : 1})
.then((postResponse) => {
const postId = postResponse.body.id;
cy.request(
"GET",
`https://jsonplaceholder.typicode.com/posts/${
postId}`)
.its("body")
.should("have.property", "title", "foo");
});
Testing Error Responses
You should also test how your API handles error cases:
cy.request({
method : "GET",
url :
"https://jsonplaceholder.typicode.com/invalid-url",
failOnStatusCode : false
}).then((response) => {
expect(response.status).to.eq(404);
});
Best Practices for Cypress API Testing
Organizing Test Files
Keep your tests organized by grouping related tests in separate files or folders. This helps in maintaining clarity and ease of access:
cypress/
e2e/
api_tests/
auth_tests.js
post_tests.js
Data Management
Use fixtures or external files to manage test data, which allows for easier test maintenance and scalability:
cy.fixture("user").then((userData) => {
cy.request("POST",
"https://jsonplaceholder.typicode.com/posts",
userData)
.then((response) => {
expect(response.status).to.eq(201);
});
});
Performance Considerations
Make your tests run efficiently by avoiding redundant requests and reusing data wherever possible. For instance, if a token is required for multiple requests, store it and reuse it.
Real-World Examples of Cypress API Testing
Testing a REST API
Here's a complete example of testing a REST API, including CRUD operations:
describe("REST API Testing with Cypress", () => {
it("Create a new post", () => {
cy.request(
"POST",
"https://jsonplaceholder.typicode.com/posts",
{title : "foo", body : "bar", userId : 1})
.then((response) => {
expect(response.status).to.eq(201);
expect(response.body)
.to.have.property("id");
});
});
it("Get a post by ID", () => {
cy.request(
"GET",
"https://jsonplaceholder.typicode.com/posts/1")
.its("body")
.should("have.property", "id", 1);
});
it("Update a post", () => {
cy.request(
"PUT",
"https://jsonplaceholder.typicode.com/posts/1",
{title : "baz", body : "qux", userId : 1})
.then((response) => {
expect(response.status).to.eq(200);
expect(response.body)
.to.have.property("title", "baz");
});
});
it("Delete a post", () => {
cy.request(
"DELETE",
"https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
expect(response.status).to.eq(200);
});
});
});
Testing a GraphQL API with Cypress
GraphQL APIs can also be tested using Cypress:
describe("GraphQL API Testing with Cypress", () => {
it("Fetch user data", () => {
cy.request({
method : "POST",
url : "https://api.example.com/graphql",
body : {
query : `
{
user(id: "1") {
name
email
}
}
`
}
}).then((response) => {
expect(response.body.data.user)
.to.have.property("name", "John Doe");
});
});
});
Conclusion
Cypress is a powerful tool for API testing, offering a robust set of features to validate API functionality, performance, and security. By following best practices and utilizing Cypress's capabilities, you can ensure that your APIs are reliable and meet the expected standards.