Sobes.tech
Middle

How can you automate API testing?

sobes.tech AI

Answer from AI

API testing automation can be performed using the following methods:

  1. Using frameworks/libraries:

    • Rest-Assured (Java): A popular library for testing REST APIs.
    • Requests (Python): A simple and powerful library for making HTTP requests.
    • SuperTest (Node.js): A library for testing HTTP servers and APIs.
    • Postman/Newman: Applications with GUI and CLI for creating and running API tests.
  2. Creating test scenarios:

    • Define positive and negative test cases for each endpoint.
    • Scenarios include sending requests with various parameters, checking response statuses (HTTP codes), response body content (JSON, XML, etc.), and headers.
  3. Data validation:

    • JSON schema validation to check the structure and data types in the response.
    • Comparing actual response values with expected ones.
  4. Data management:

    • Using test data stored in files (JSON, CSV) or databases.
    • Preparing data before test execution and cleaning up afterward (if required).
  5. Integration with CI/CD systems:

    • Setting up automated API tests to run on each code change or regularly (e.g., every evening).
    • Using Jenkins, GitLab CI, GitHub Actions, etc.
  6. Reporting:

    • Generating detailed reports on test results (e.g., Allure Framework).

Example of using Rest-Assured:

import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class ApiTests {

    @Test
    public void testGetUserById() {
        // Base URL of the API
        RestAssured.baseURI = "https://reqres.in/api";

        // Sending GET request
        given()
                .when()
                .get("/users/2")
                .then()
                .statusCode(200)  // Check response status
                .body("data.id", equalTo(2))  // Check response body value
                .body("data.first_name", equalTo("Janet"));
    }
}

Example of using Requests (Python):

import requests

def test_get_user_by_id():
    url = "https://reqres.in/api/users/2"
    response = requests.get(url)

    assert response.status_code == 200  # Check response status
    data = response.json()
    assert data['data']['id'] == 2  # Check response body value
    assert data['data']['first_name'] == 'Janet'
How can you automate API testing? — QA / QA Automation - sobes.tech