DEV Community

Marant7
Marant7

Posted on

API Testing Frameworks

In modern software development, API testing is crucial for ensuring the reliability and quality of web services. Let's explore some of the most popular frameworks with practical code examples.

Rest-Assured: RESTful API Testing in Java

Rest-Assured stands out for its fluent and expressive syntax, ideal for REST API testing in Java.

@Test
public void testGetUsers() {
    given()
        .header("Content-Type", "application/json")
    .when()
        .get("https://api.example.com/users")
    .then()
        .statusCode(200)
        .body("users.size()", greaterThan(0))
        .body("users[0].name", notNullValue());
}

@Test
public void testCreateUser() {
    User user = new User("John", "john@email.com");

    given()
        .body(user)
        .contentType(ContentType.JSON)
    .when()
        .post("https://api.example.com/users")
    .then()
        .statusCode(201)
        .body("id", notNullValue())
        .body("name", equalTo("John"));
}

Enter fullscreen mode Exit fullscreen mode

Postman: Codeless Testing

Postman allows creating automated tests using JavaScript in its graphical interface:

// Test to verify successful response and data structure
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Response contains correct data", function () {
    var jsonData = pm.response.json();

    pm.expect(jsonData).to.have.property('users');
    pm.expect(jsonData.users).to.be.an('array');
    pm.expect(jsonData.users[0]).to.have.property('id');
    pm.expect(jsonData.users[0]).to.have.property('name');
});

// Test to validate JSON schema
var schema = {
    "type": "object",
    "properties": {
        "id": { "type": "number" },
        "name": { "type": "string" },
        "email": { "type": "string" }
    },
    "required": ["id", "name", "email"]
};

pm.test("Schema is valid", function() {
    var jsonData = pm.response.json();
    pm.expect(tv4.validate(jsonData, schema)).to.be.true;
});
Enter fullscreen mode Exit fullscreen mode

Karate DSL: Simplified BDD Testing

Karate DSL allows writing tests in Gherkin format without requiring step definitions:

Feature: User API Tests

Background:
    * url 'https://api.example.com'
    * header Accept = 'application/json'

Scenario: Get list of users
    Given path 'users'
    When method get
    Then status 200
    And match response == '#array'
    And match each response contains { id: '#number', name: '#string' }

Scenario: Create new user
    Given path 'users'
    And request { name: 'Anna', email: 'anna@email.com' }
    When method post
    Then status 201
    And match response contains { id: '#number', name: 'Anna' }
Enter fullscreen mode Exit fullscreen mode

PyRestTest: YAML Testing

PyRestTest allows defining tests in YAML files, making them more readable:

- config:
    - testset: "User API Tests"
    - base_url: "https://api.example.com"

- test:
    - name: "Get users"
    - url: "/users"
    - method: "GET"
    - headers: {'Content-Type': 'application/json'}
    - validators:
        - compare: {header: "status_code", comparator: "eq", expected: 200}
        - json_schema: {schema: {type: "array"}}

- test:
    - name: "Create user"
    - url: "/users"
    - method: "POST"
    - body: '{"name": "Charles", "email": "charles@email.com"}'
    - headers: {'Content-Type': 'application/json'}
    - validators:
        - compare: {header: "status_code", comparator: "eq", expected: 201}
        - compare: {jsonpath_mini: "name", comparator: "eq", expected: "Charles"}
Enter fullscreen mode Exit fullscreen mode

JMeter: Performance and Functional Testing

While JMeter is known for load testing, it can also perform functional API testing:

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2">
  <hashTree>
    <HTTPSamplerProxy>
      <stringProp name="HTTPSampler.domain">api.example.com</stringProp>
      <stringProp name="HTTPSampler.path">/users</stringProp>
      <stringProp name="HTTPSampler.method">GET</stringProp>
      <boolProp name="HTTPSampler.follow_redirects">true</boolProp>

      <HeaderManager>
        <collectionProp name="HeaderManager.headers">
          <elementProp name="">
            <stringProp name="Header.name">Content-Type</stringProp>
            <stringProp name="Header.value">application/json</stringProp>
          </elementProp>
        </collectionProp>
      </HeaderManager>

      <JSONPathAssertion>
        <stringProp name="JSON_PATH">$[0].id</stringProp>
        <stringProp name="EXPECTED_VALUE">1</stringProp>
        <boolProp name="JSONVALIDATION">true</boolProp>
      </JSONPathAssertion>
    </HTTPSamplerProxy>
  </hashTree>
</jmeterTestPlan>
Enter fullscreen mode Exit fullscreen mode

Conclusions and Best Practices

Each framework has its particular strengths:

  • Rest-Assured: Excellent for Java teams needing TestNG/JUnit integration
  • Postman: Ideal for quick testing and teams with less programming experience
  • Karate DSL: Perfect for teams using BDD methodology
  • PyRestTest: Good option for simple tests with YAML configuration
  • JMeter: Optimal when combining functional and performance testing

Recommendations:

  • Test Independence: Each test should be able to run in isolation
  • Test Data: Use specific test data, not production data
  • Complete Assertions: Verify not just status codes, but also response structure and content
  • Documentation: Keep examples and documentation up to date
  • Continuous Integration: Incorporate tests into the CI/CD pipeline

Top comments (1)

Collapse
 
erick_javiersalinascond profile image
Erick Javier SALINAS CONDORI

nice examples bro