KatInterview

Paginated API Fetching and Data Merging

Arrays & HashingModel answer
MediumModel answerArrays & Hashingpaginationhttp-requestshash-table

Last updated

Fetch paginated JSON payloads from two separate endpoints, defensively clean and transform records, and merge them on a common key preserving the original sequence.

You are tasked with writing a Python function get_enriched_records(api_a_url, api_b_url) that aggregates and enriches data from two paginated web APIs.

API A Specification

Endpoint api_a_url returns paginated JSON structured as:

{
  "data": [
    {"id": 1, "ref_id": "x1"},
    {"id": 2, "ref_id": "x2"}
  ],
  "next_page": 2
}
  • Parameters: Pages are fetched using standard HTTP GET query parameters formatted as ?page=N starting from page 1.
  • Termination: When next_page is null or missing, there are no more pages.

API B Specification

Endpoint api_b_url returns paginated JSON structured as:

{
  "data": [
    {"ref_id": "x1", "target_field": "value1"},
    {"ref_id": "x2", "target_field": "value2"}
  ],
  "next_page": null
}

Requirements

  1. Request all pages from both api_a_url and api_b_url.
  2. Perform an inner join between the dataset from API A and API B matching on the ref_id attribute.
  3. Return a list of output objects formatted as: [{"id": <id>, "target_field": <value>}, ...]
  4. Retain the exact order of elements as they appeared in API A.
  5. Omit a record if any of the following apply:
    • ref_id is missing or None.
    • id (from API A) is missing or None.
    • No matching ref_id exists in the dataset collected from API B.
    • The associated target_field in API B is None, an empty string "", or contains only whitespace characters.
  6. Handle missing keys, null payloads, malformed JSON objects, and empty list pages safely without raising exceptions or entering infinite loops.

Assume the HTTP library requests is available and mockable for testing.

Hints

Hint 1

To retain order while performing O(1) matching, consume API B fully into a dictionary lookup map before iterating through API A.

Hint 2

Be careful with falsy values like 0 or False—a simple `if not target_field:` check will accidentally drop valid non-string data.

Hint 3

Safeguard your HTTP page retrieval loop with a set of visited page numbers to prevent infinite loops if an upstream API has a cyclic `next_page` pointer.