Back to Test Automation
2026-02-165 min read

API Testing in Automation

Learn API Testing in Automation step by step with clear examples and exercises.

Title: API Testing in Automation using JavaScript (Selenium, Cypress, Playwright)

Why This Matters

API testing plays a crucial role in ensuring the functionality of your application's backend services. It helps to verify that APIs are working as expected and provides a way to test various scenarios without relying on the UI. Automating API tests can save time, reduce human error, and improve overall software quality. This lesson will demonstrate how to perform API testing using popular JavaScript tools like Selenium, Cypress, and Playwright.

The Importance of API Testing

  • Ensures backend services function correctly
  • Allows for testing various scenarios without relying on the UI
  • Reduces human error and saves time
  • Improves overall software quality

Prerequisites

  • Basic understanding of HTTP requests (GET, POST, PUT, DELETE)
  • Familiarity with JavaScript ES6 syntax
  • Knowledge of at least one front-end framework or library (React, Angular, Vue.js)
  • Understanding of test-driven development (TDD) concepts
  • Familiarity with one or more API testing tools (Selenium, Cypress, Playwright)
  • Experience working with REST APIs and understanding JSON data format

Core Concept

API testing involves sending requests to an API's endpoints and verifying the responses to ensure they meet your expectations. The most common HTTP methods used in API testing are GET, POST, PUT, and DELETE.

GET: Retrieves data from a specified endpoint. Example: https://api.example.com/users?id=1

POST: Sends data to an endpoint for creation or modification. Example: https://api.example.com/users with JSON body: { "name": "John Doe", "email": "john@example.com" }

PUT: Updates existing data on an endpoint. Example: https://api.example.com/users/1 with JSON body: { "name": "Jane Doe", "email": "jane@example.com" }

DELETE: Removes data from an endpoint. Example: https://api.example.com/users/1

To perform API testing, you can use various tools such as Selenium (with WebDriverJS), Cypress, and Playwright. These tools allow you to write tests in JavaScript that simulate user interactions with your application's APIs.

Understanding API Responses

  • Verify response status codes
  • Check for expected data structure and content
  • Handle errors and exceptions appropriately
  • Compare JSON data using deep equality checks (e.g., expect(actualResponse).toEqual(expectedResponse))

Worked Example

Let's create a simple test using Selenium to perform an API GET request, verify the response status code, and compare the response data with expected data.

  1. Install WebDriverJS: npm install webdriverjs
  2. Create a new JavaScript file (e.g., api_test.js) and import WebDriverJS:
const { Builder } = require('selenium-webdriver');
  1. Define the API endpoint, expected response data, and status code:
const endpoint = 'https://jsonplaceholder.typicode.com/posts';
const expectedResponseData = [
{ id: 1, title: 'sunt aut facere', body: 'quia et suscipit\nsuscipit repellat provident sapiente' },
// ... more expected responses
];
const expectedStatusCode = 200;
  1. Create a function to perform the API GET request, verify the response status code and data, and handle errors:
async function testApi() {
const driver = await new Builder().forBrowser('chrome').build();
try {
const response = await driver.get(endpoint);
const actualStatusCode = response.status;
const actualResponseData = await response.json();

// Check that the API returned the expected status code
expect(actualStatusCode).toEqual(expectedStatusCode);

// Iterate through each post and compare the title and body with the expected data
for (let i = 0; i < actualResponseData.length; i++) {
const post = actualResponseData[i];
const expectedPost = expectedResponseData[i];

expect(post).toEqual(expectedPost);
}
} catch (error) {
console.error('Error while testing API:', error);
} finally {
await driver.quit();
}
}
  1. Call the test function to run the test:
testApi();

Common Mistakes

  1. Not properly handling API errors or exceptions.
  2. Overlooking differences between the expected and actual responses due to formatting issues (e.g., whitespace, case sensitivity).
  3. Failing to clean up resources after tests (e.g., closing database connections, deleting temporary files).
  4. Writing brittle tests that are sensitive to changes in the API's implementation.
  5. Neglecting to test edge cases and invalid input scenarios.

Common Mistakes Expanded

  1. Not Properly Handling API Errors or Exceptions
  • Not catching exceptions, leading to unhandled promises and test failures
  • Ignoring non-200 status codes without proper error handling
  1. Overlooking Differences Between the Expected and Actual Responses
  • Failing to handle differences in data format (e.g., JSON vs XML)
  • Overlooking minor discrepancies due to formatting issues like whitespace or case sensitivity
  1. Failing to Clean Up Resources After Tests
  • Leaving open database connections, leading to resource exhaustion and potential data corruption
  • Failing to delete temporary files, causing disk space issues and test flakiness
  1. Writing Brittle Tests
  • Hardcoding API endpoints or URL parameters, making tests sensitive to changes in the API's implementation
  • Relying on specific implementation details instead of testing the intended behavior
  1. Neglecting to Test Edge Cases and Invalid Input Scenarios
  • Failing to test error handling for invalid input data
  • Overlooking edge cases like missing or extra parameters in API requests

Practice Questions

  1. Write a Cypress test to perform an API POST request with JSON data, verify the response status code, and check if the created resource ID is within a specified range.
  2. Implement a Playwright test to update an existing resource using PUT, verify the updated data in the response, and ensure that the API returns the correct status code (e.g., 200 for success).
  3. Create a test suite that tests multiple endpoints of your application's API using Selenium, Cypress, or Playwright, including edge cases and invalid input scenarios.

FAQ

What is the difference between API testing and UI testing?

  • API testing focuses on verifying the functionality of an application's backend services, while UI testing checks the user interface and interactions.

Can I use Selenium for API testing?

  • Yes, you can use Selenium with WebDriverJS to perform API tests by sending HTTP requests directly or by interacting with a web page that exposes an API. However, other tools like Cypress and Playwright are more suited for API testing due to their dedicated support for this purpose.

What is the best tool for API testing in JavaScript?

  • The choice of tool depends on your specific needs and preferences. Selenium, Cypress, and Playwright all have their strengths and can be used effectively for API testing. It's essential to consider factors like ease of use, community support, and integration with other tools in your tech stack when making a decision.
API Testing in Automation | Test Automation | XQA Learn