Sobes.tech
Junior

How will you verify that the correct fields have been returned?

sobes.tech AI

Answer from AI

You can verify that the correct fields are returned in several ways, depending on the response type (JSON, XML, etc.), the tool used, and the level of testing (API, E2E):

  1. Response schema validation:

    • The most reliable method.
    • A schema (JSON Schema, XML Schema) describing the structure and data types of the expected response is created.
    • The response is validated against this schema.
    • Ensures the presence/absence of fields, their types, and optionally, regular expressions for values.
    // Example JSON Schema for a user response
    {
      "type": "object",
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "string" },
        "email": { "type": "string", "format": "email" }
      },
      "required": ["id", "name", "email"]
    }
    
  2. Direct check of field presence/absence and values:

    • Parsing the response.
    • Checking that each expected field is present.
    • Checking that unwanted fields are absent.
    • Checking data types of fields.
    • Checking field values (against specific values, regex, range, etc.).
    # Example of checking a JSON response in Python (using requests and pytest)
    import requests
    import pytest
    
    def test_user_response_fields():
        response = requests.get("http://api.example.com/users/1")
        assert response.status_code == 200
        data = response.json()
    
        # Check for presence of fields
        assert "id" in data
        assert "name" in data
        assert "email" in data
    
        # Check for absence of unwanted fields (e.g., 'password')
        assert "password" not in data
    
        # Check data types of fields
        assert isinstance(data["id"], int)
        assert isinstance(data["name"], str)
        assert isinstance(data["email"], str)
    
        # Check values (example)
        assert data["id"] > 0
        assert "@" in data["email"] # Basic email format check
    
  3. Comparison with a reference (Golden Master / Snapshot Testing):

    • A known correct response (reference) is saved.
    • The current response is compared with the reference.
    • Useful for checking structural stability but less flexible for expected data changes.
  4. Using specialized libraries/frameworks:

    • RestAssured (Java)
    • Postman (Newman): allows writing tests in JavaScript, including schema and field checks.
    • Pytest/unittest with libraries for JSON/XML handling.

The choice of method depends on the complexity of the response structure, accuracy requirements, and the technology stack used. Schema validation is considered the gold standard for API testing as it covers all aspects of structure and data types.