Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Validate JSON API Response
00:00
5 left

Validate JSON API Response

MediumPython

Problem

TikTok Solutions Engineers often validate responses from TikTok for Business APIs before passing them to downstream integrations. Given a parsed JSON response and a recursive schema, determine whether the response has the required structure and data types.

Implement validate_response(response, schema) and return True only when the entire response matches the schema. Extra response fields are allowed. The schema supports object, array, string, integer, number, boolean, and null types. Object schemas may contain required and properties; array schemas may contain items.

Formal Specification

  • response: A Python value produced by parsing JSON, such as a dictionary, list, string, number, boolean, or None.
  • schema: A valid dictionary describing one expected value. Each schema node has a type, and may contain nested properties, required, or items fields.
  • Return a Python boolean. Return False for a missing required field, an incorrect type, or any invalid nested value.
  • A boolean is not considered an integer or number, even though Python subclasses bool from int.

Examples

Example 1

response = {"data": {"video_id": "v1", "views": 120}}, with an object schema requiring video_id as a string and views as an integer, returns True because both required fields have the expected types.

Example 2

response = {"items": [{"id": "a"}, {"id": 7}]}, with an array schema requiring every id to be a string, returns False because the second item violates the nested schema.

Constraints

  • The schema contains at most 10^4 nodes
  • The response contains at most 10^4 nested values
  • Nesting depth is at most 100
  • Supported types are object, array, string, integer, number, boolean, and null
  • Extra response fields are allowed
  • The schema is valid

Function Signature

def validate_response(response, schema):
Interviewer

Your question is Validate JSON API Response. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.