intermediate24 min

Validating JSON Responses Against a Schema (Lab)

A hands-on lab: check a response's actual shape against what it's supposed to be — field presence, correct types, and nothing extra or missing.

What you'll learn

  • Write a schema check that verifies required fields and their types
  • Distinguish a missing field from a field with the wrong type
  • Explain why schema validation catches defects a single hand-picked example wouldn't

Prerequisites

Explanation

Checking one specific field's value ("does body.name equal 'Ada'?") proves that one field is right in that one response. It says nothing about whether the response's overall shape is reliable: is id always a number, or does it sometimes come back as a string? Is email always present, or does it silently disappear for some users? Schema validation checks the whole shape at once: which fields must be present, what type each one must be, and — often overlooked — whether unexpected extra fields show up that nobody documented.

A minimal schema for a user resource might specify: id is a required number, name is a required string, email is a required string, isActive is a required boolean. A schema-validating test doesn't hand-pick one example response and eyeball it — it runs the same structural check against every response the API returns, catching a defect like "sometimes id comes back as the string "42" instead of the number 42" that a single spot-check would likely never happen to catch, because the buggy case might only occur for some accounts, some load conditions, or some code paths.

Two distinct failure categories matter here, and a good schema check reports them separately rather than lumping them into one vague "invalid" result: a missing field (the key isn't present at all) is a different defect from a wrong type (the key is present, but holds a string where a number was expected) — they often point to different root causes in the server code, so conflating them in a bug report makes the report less useful.

Real-world API testing tools (like AJV for JSON Schema, or Pact for contract testing) automate exactly this kind of check against a formal specification. The version practiced here — a small, explicit function checking required fields and types — is the same underlying idea, simplified enough to reason about and write by hand.

Example

A small schema-validation function distinguishing missing fields from wrong-type fields, run against a simulated (fixture) API response.

const schema = {
  id: "number",
  name: "string",
  isActive: "boolean",
};

function validateSchema(obj, schema) {
  const errors = [];
  for (const [field, expectedType] of Object.entries(schema)) {
    if (!(field in obj)) {
      errors.push(`missing field: ${field}`);
    } else if (typeof obj[field] !== expectedType) {
      errors.push(`${field} should be ${expectedType}, got ${typeof obj[field]}`);
    }
  }
  return errors;
}

// Simulated response -- not a real network call.
const response = { id: "42", name: "Ada" };
console.log(validateSchema(response, schema));
// ["id should be number, got string", "missing field: isActive"]

Try it yourself

Fix the simulated response so it matches the schema exactly, then re-run — the errors array should become empty.

Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.

Loading editor…

Guided exercise

Guided exercise

Using the schema and validateSchema function already defined, run it against simulatedResponse and store the result in errors. simulatedResponse is missing the 'price' field and has 'inStock' as a string instead of a boolean.

Checks: reports the missing price field · reports inStock's wrong type · does not report name, which is correct

Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.

Loading editor…

Stuck? Get a hint.

Independent exercise

Independent exercise

Write a function countErrorsByType(errors) that takes the array of error strings produced by validateSchema-style checks (each either starts with 'missing field' or contains 'wrong type') and returns { missing: N, wrongType: N }.

Checks: correctly counts missing-field errors · correctly counts wrong-type errors · handles an empty errors array

Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.

Loading editor…

Stuck? Get a hint.

Common mistakes

  • Spot-checking one field's value in one example response and calling the API's response shape "tested," instead of validating the whole structure systematically.
  • Lumping a missing field and a wrong-type field into one generic "invalid" result, losing information that would help diagnose the actual bug.
  • Never checking for unexpected extra fields, which can quietly leak internal data that was never meant to be exposed.

Knowledge check

Knowledge check

1. What does schema validation check that a single hand-picked field check does not?
2. Why should a missing field and a wrong-type field be reported as distinct kinds of errors?
3. Why might checking for unexpected extra fields in a response matter?

Takeaway

Schema validation checks a response's entire shape systematically — required fields, correct types, and unexpected extras — catching structural defects that spot-checking a single example would likely miss.

Summary

This lab practiced writing a schema-validation check that distinguishes missing fields from wrong-type fields, and explained why systematic shape validation beats one-off field checks.

References

Your notes

Notes save automatically.

Finished this lesson?

Mark it complete to track your progress and schedule a future review.