JSON and API Response Validation

Jul 5, 2024

JSON and API Response Validation

Overview of JSON

  • JSON: JavaScript Object Notation
  • JSON Path: Used to identify and locate nodes/data in JSON
  • JSON in API: Key element in API responses, used for validation

Response Validation Components

  1. Status Code
  2. Headers
  3. Cookies
  4. Response Time
  5. Response Body

Importance of Understanding Response Types

  • Testing APIs: Understanding request and response types for validation is crucial
  • Pre-run API: Analyze data beforehand to set proper validation points

Key Validation Points

  1. Status Code Validation
    • Code showing success or failure of the request
    • Methods: pm.response.to.have.status(expectedCode), pm.expect(pm.response.code).to.be.oneOf([200, 201])
  2. Headers Validation
    • Important headers to check: content-type, etc.
    • Methods: pm.expect(pm.response.headers.get('Content-Type')).to.equal('application/json')
  3. Cookies Validation
    • Checking presence and value of cookies
    • Methods: pm.expect(pm.cookies.has('cookieName')).to.be.true, pm.expect(pm.cookies.get('cookieName')).to.eql('expectedValue')
  4. Response Time Validation
    • Validate response time to ensure prompt API response
    • Method: pm.expect(pm.response.responseTime).to.be.below(expectedMilliseconds)

Response Body Validation

Asserting Value Types

  • Purpose: Ensures data types of JSON fields are correct
  • Implementation:
    • Capture response: const jsonData = pm.response.json();
    • Example:
      pm.expect(jsonData.id).to.be.a('number');
      pm.expect(jsonData.name).to.be.a('string');
      pm.expect(jsonData.courses).to.be.an('array');
      

Asserting Array Properties

  • Purpose: Ensures arrays have expected values
  • Methods:
    • Include method: pm.expect(jsonData.courses).to.include('Java');
    • Have members: pm.expect(jsonData.courses).to.have.members(['Java', 'Selenium']);

Validating JSON Fields

  • Purpose: Verifies value correctness of specific JSON fields
  • Example:
    pm.expect(jsonData.id).to.eql(1);
    pm.expect(jsonData.name).to.eql('John');
    pm.expect(jsonData.courses[0]).to.eql('Java');
    pm.expect(jsonData.courses[1]).to.eql('Selenium');
    

Validating JSON Schema

  • Purpose: Validates response against predefined schema
  • Schema Design: Specifies data types and requirements for each field
  • Tools: Online JSON schema generator
  • Method:
    const schema = { /* schema content */ };
    const tv4 = require('tv4');
    pm.test('Schema is valid', function() {
      pm.expect(tv4.validate(jsonData, schema)).to.be.true;
    });
    

Summary

  • Always capture and prepare the JSON response before validation
  • Specific validation functions for headers, cookies, response time, and body
  • Use of chai and pm libraries for implementing validation in Postman