Paginated Record Enrichment Across Two Endpoints

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement paginated HTTP retrieval and in-memory record joining across two JSON endpoints:

  • http_get_json(url, params) sends an HTTP GET request with params encoded as query parameters on url (handling URLs that may already contain ?), decodes the UTF-8 JSON payload, and lets transport or non-2xx HTTP errors propagate.
  • get_enriched_records(api_a_url, api_b_url, fetch_json=None) fetches every page from both endpoints, joins their records on "ref_id", and returns a list of {"id": <id>, "target_field": <value>} dictionaries. When fetch_json is omitted or None, use http_get_json.

Both endpoints paginate starting at {"page": 1} and return JSON objects shaped like:

{
  "data": [ ... ],
  "next_page": 2
}

Continue requesting {"page": next_page} until "next_page" is null, absent, invalid, or repeats an already-visited page token.

  • Each valid record from api_a_url has "id" and "ref_id".
  • Each valid record from api_b_url has "ref_id" and "target_field".

Your implementation must satisfy these exact rules:

  1. Full pagination: Traverse all reachable pages from api_a_url and api_b_url (including across empty intermediate "data": [] pages when "next_page" still advances).
  2. Order preservation: Emit output dictionaries in the exact record order returned by api_a_url. If api_a_url contains multiple records with the same "ref_id", enrich each qualifying record.
  3. First usable match in api_b_url: If api_b_url contains multiple records with the same "ref_id", use the first one whose "target_field" is valid.
  4. Filtering invalid records and blank values: Skip a record when:
    • "id" is missing or null on the api_a_url record;
    • "ref_id" is missing, null, empty, whitespace-only, a boolean, or unhashable (such as a list or object);
    • no matching "ref_id" with a valid "target_field" exists in api_b_url;
    • "target_field" is missing, null, "", or whitespace-only (keep non-string falsy values such as 0 or False, and preserve non-empty strings without stripping their padding).
  5. Defensive payload handling: Never crash on missing dictionary keys, null page bodies, non-list "data" fields, non-object items inside "data", invalid "next_page" values (0, negative integers, booleans, blank strings, lists), or pagination cycles.

Examples

Example 1

Input:

  • api_a_url responses:
    • Page 1: {"data": [{"id": 101, "ref_id": "sku-9"}, {"id": 102, "ref_id": "sku-4"}], "next_page": 2}
    • Page 2: {"data": [{"id": 103, "ref_id": "sku-7"}], "next_page": null}
  • api_b_url responses:
    • Page 1: {"data": [{"ref_id": "sku-4", "target_field": "warehouse-west"}], "next_page": 2}
    • Page 2: {"data": [{"ref_id": "sku-9", "target_field": "warehouse-east"}], "next_page": null}

Output:

[
  {"id": 101, "target_field": "warehouse-east"},
  {"id": 102, "target_field": "warehouse-west"}
]

Explanation: Record 101 ("sku-9") joins with page 2 of api_b_url ("warehouse-east"), and record 102 ("sku-4") joins with page 1 of api_b_url ("warehouse-west"). Record 103 ("sku-7") has no match in api_b_url and is dropped. The returned list preserves api_a_url's order (101 before 102).

Example 2

Input:

  • api_a_url responses:
    • Page 1: {"data": [{"id": 20, "ref_id": "acct-a"}, {"id": 21}, {"id": 22, "ref_id": "acct-b"}, {"id": 23, "ref_id": "acct-c"}], "next_page": null}
  • api_b_url responses:
    • Page 1: {"data": [{"ref_id": "acct-a", "target_field": " "}, {"ref_id": "acct-a", "target_field": "active"}, {"ref_id": "acct-b", "target_field": null}, {"ref_id": "acct-c", "target_field": 0}], "next_page": null}

Output:

[
  {"id": 20, "target_field": "active"},
  {"id": 23, "target_field": 0}
]

Explanation: For "acct-a", the whitespace-only " " entry is ignored so record 20 receives "active". Record 21 has no "ref_id" and record 22 only maps to null, so both are skipped. Record 23 keeps 0 because numeric zero is a valid non-blank value.

Constraints

  • Valid "ref_id" values are non-boolean integers or non-blank strings.
  • Valid "next_page" tokens are positive integers (>= 1) or non-blank cursor strings; pagination always starts with {"page": 1}.
  • Total records across all pages of both APIs can reach tens of thousands, so joining records should run in O(A + B) average local CPU time rather than O(A * B).

Step-by-step walkthrough

  1. Clarify the API contract and edge-case rules

    Before writing any code, let's pin down exactly what comes in, what goes out, and how messy data should behave:

    • Input: Two paginated HTTP endpoints (api_a_url and api_b_url). We start each endpoint at page=1 and keep following "next_page" until "next_page" is null, missing, or invalid.
    • Output: A list of {"id": <id>, "target_field": <value>} dictionaries in the exact record order of API A.
    • Defensive filtering rules:
      • Skip any record that is not a JSON object (dict), or any API A record whose "id" is missing/None or whose "ref_id" is missing, blank, or unhashable.
      • Skip any match where API B has no record for "ref_id", or where API B's "target_field" is missing, null, "", or whitespace-only (" ").
      • Keep non-string falsy values such as 0 or False in "target_field", and preserve valid strings unchanged (" v6 " stays " v6 ").
      • If API B contains duplicate "ref_id" entries, take the first usable "target_field" (so an earlier blank entry never hides a later valid one). If API A repeats a "ref_id", enrich every matching API A record.
  2. Keep HTTP behind an injectable helper

    The prompt notes that the test harness mocks API responses. Instead of hard-coding network calls deep inside our join logic, we accept an optional fetch_json(url, params) callable (dependency injection — passing an external dependency in as a parameter so tests can supply a fast in-memory fake while callers get real HTTP by default).

    For the default http_get_json implementation, Python's built-in urllib.request.urlopen handles GET requests cleanly: - If url already contains a ? (for example https://host/items?env=prod), we glue urlencode(params) on with "&"; otherwise we use "?". - We set timeout=10 so an unresponsive server cannot hang the process forever. - We intentionally let HTTP 4xx/5xx (HTTPError) and network errors (URLError) raise: if page 2 of API B fails over the network, returning partial data silently would look like genuine missing matches!

    from typing import Any, Callable, Dict, List, Optional
    import json
    import urllib.parse
    import urllib.request
    
    # FetchJson(url, params) sends a GET request with query parameters and returns
    # the decoded JSON payload. Tests inject a fake; production defaults to HTTP.
    FetchJson = Callable[[str, Dict[str, Any]], Any]
    
    
    def http_get_json(url: str, params: Dict[str, Any]) -> Any:
        """GET `url` with `params` encoded as query parameters and decode JSON."""
        query_string = urllib.parse.urlencode(params)
        if query_string:
            # Use "&" when `url` already has query parameters, otherwise "?".
            separator = "&" if "?" in url else "?"
            full_url = f"{url}{separator}{query_string}"
        else:
            full_url = url
    
        # `urlopen` raises HTTPError on non-2xx statuses and URLError on network errors;
        # let those propagate so callers never mistake a failed page fetch for empty data.
        with urllib.request.urlopen(full_url, timeout=10) as response:
            raw_bytes = response.read()
            return json.loads(raw_bytes.decode("utf-8"))
    
  3. Write explicit validation helpers for values, keys, and page tokens

    Messy JSON payloads trip up careless Python checks in three classic ways:

    1. if not value: drops 0: Writing if not target_field: treats target_field = 0 as blank. Instead, _is_blank(value) checks specifically for None and strings that become "" after .strip().
    2. bool is a subclass of int in Python: isinstance(True, int) evaluates to True, and True == 1 / False == 0 in Python dictionaries! Checking isinstance(value, bool) first inside _is_usable_key ensures "ref_id": true never collides with "ref_id": 1, and "next_page": false never triggers ?page=False.
    3. Unhashable JSON types and invalid page numbers: A malformed "ref_id": ["sku-9"] is a list and would crash with TypeError: unhashable type: 'list' on dict lookup. Accepting only non-bool int and non-blank str makes every accepted key safe to hash, and _is_valid_next_page additionally rejects integers < 1 (such as "next_page": 0).
    def _is_blank(value: Any) -> bool:
        """Return True only when `value` is None, empty string, or whitespace-only string."""
        # Check None and str explicitly instead of `if not value:` so valid falsy
        # values like `0` or `False` in `target_field` are NOT discarded.
        if value is None:
            return True
        if isinstance(value, str):
            return value.strip() == ""
        return False
    
    
    def _is_usable_key(value: Any) -> bool:
        """Return True for a valid `ref_id` or page token (non-bool int or non-blank str)."""
        # Reject bool BEFORE checking int: in Python `bool` subclasses `int`, and
        # `True == 1` / `False == 0` would collide with integer keys in dicts/sets!
        if isinstance(value, bool):
            return False
        if isinstance(value, int):
            return True
        if isinstance(value, str):
            return value.strip() != ""
        # Lists and dicts are unhashable and cannot serve as join keys.
        return False
    
    
    def _is_valid_next_page(value: Any) -> bool:
        """Return True when `next_page` is a positive page number or non-blank cursor string."""
        if not _is_usable_key(value):
            return False
        # Pagination starts at page 1, so 0 or negative integers mean "no next page".
        if isinstance(value, int) and value < 1:
            return False
        return True
    
  4. Paginate defensively with cycle protection

    Both endpoints share the exact same envelope shape ({"data": [...], "next_page": ...}), so one fetch_all_records helper handles both APIs.

    Walk through what can go wrong on any page response and how the loop handles each case: - body is None or not a dict: We cannot read "data" or "next_page", so break. - body.get("data") is missing, None, or "not a list": Skip record extraction for this page, without breaking — an intermediate page is allowed to be empty ("data": []) while "next_page": 3 still points to more data! - An element inside "data" is None, 7, or "junk": Only append items where isinstance(item, dict). - Buggy server returns a cycle (page 1 -> 2 -> 1): A seen_pages set records every page token we have already requested and stops immediately if next_page in seen_pages.

    def fetch_all_records(url: str, fetch_json: FetchJson) -> List[Dict[str, Any]]:
        """Fetch every page from `url` and return all dict records in page order."""
        # records: flat list of validated record dicts, e.g. [{"id": 101, "ref_id": "sku-9"}]
        records: List[Dict[str, Any]] = []
        # seen_pages: set of page tokens already requested, e.g. {1, 2}, to stop cycles
        seen_pages = set()
        current_page: Any = 1
    
        while True:
            seen_pages.add(current_page)
            body = fetch_json(url, {"page": current_page})
            if not isinstance(body, dict):
                # Null or non-object JSON payload: nothing readable and no next_page link.
                break
    
            # Extract valid dict items even if `data` is missing, null, or contains junk;
            # do NOT break when `data` is empty because a later page may still hold records.
            data = body.get("data")
            if isinstance(data, list):
                for item in data:
                    if isinstance(item, dict):
                        records.append(item)
    
            next_page = body.get("next_page")
            if not _is_valid_next_page(next_page) or next_page in seen_pages:
                # Stop at the end of pagination (`null`/missing) or on a repeated page bug.
                break
            current_page = next_page
    
        return records
    
  5. Index API B in a dictionary and join in API A's order

    If API A has a records and API B has b records, scanning all of b_records for each record in a_records takes O(a * b) time (10,000 * 10,000 = 100,000,000 checks). Instead, we perform an in-memory hash join:

    1. Build value_by_ref from b_records in one O(b) pass: Map each valid ref_id to its first non-blank target_field.
    2. Scan a_records in one O(a) pass: Look up each A record's ref_id in value_by_ref in O(1) average time. Because we iterate over a_records (and never over value_by_ref), the output automatically preserves API A's exact order!

    Trace this on Example 1 from the statement:

    API A pages:
      page 1 -> [{"id": 101, "ref_id": "sku-9"}, {"id": 102, "ref_id": "sku-4"}], next_page: 2
      page 2 -> [{"id": 103, "ref_id": "sku-7"}],                                 next_page: null
    
    API B pages:
      page 1 -> [{"ref_id": "sku-4", "target_field": "warehouse-west"}],          next_page: 2
      page 2 -> [{"ref_id": "sku-9", "target_field": "warehouse-east"}],          next_page: null
    
    Step 1 (Index B):
      - ("sku-4", "warehouse-west") -> valid -> value_by_ref = {"sku-4": "warehouse-west"}
      - ("sku-9", "warehouse-east") -> valid -> value_by_ref = {"sku-4": "warehouse-west", "sku-9": "warehouse-east"}
    
    Step 2 (Walk A in order):
      - id=101, ref_id="sku-9" -> found "warehouse-east" -> emit {"id": 101, "target_field": "warehouse-east"}
      - id=102, ref_id="sku-4" -> found "warehouse-west" -> emit {"id": 102, "target_field": "warehouse-west"}
      - id=103, ref_id="sku-7" -> missing in B           -> skip
    
    Output: [{"id": 101, "target_field": "warehouse-east"}, {"id": 102, "target_field": "warehouse-west"}]
    
  6. Assemble the complete solution

    Putting all pieces together gives the complete solution.py:

    from typing import Any, Callable, Dict, List, Optional
    import json
    import urllib.parse
    import urllib.request
    
    # FetchJson(url, params) sends a GET request with query parameters and returns
    # the decoded JSON payload. Tests inject a fake; production defaults to HTTP.
    FetchJson = Callable[[str, Dict[str, Any]], Any]
    
    
    def http_get_json(url: str, params: Dict[str, Any]) -> Any:
        """GET `url` with `params` encoded as query parameters and decode JSON."""
        query_string = urllib.parse.urlencode(params)
        if query_string:
            # Use "&" when `url` already has query parameters, otherwise "?".
            separator = "&" if "?" in url else "?"
            full_url = f"{url}{separator}{query_string}"
        else:
            full_url = url
    
        # `urlopen` raises HTTPError on non-2xx statuses and URLError on network errors;
        # let those propagate so callers never mistake a failed page fetch for empty data.
        with urllib.request.urlopen(full_url, timeout=10) as response:
            raw_bytes = response.read()
            return json.loads(raw_bytes.decode("utf-8"))
    
    
    def _is_blank(value: Any) -> bool:
        """Return True only when `value` is None, empty string, or whitespace-only string."""
        # Check None and str explicitly instead of `if not value:` so valid falsy
        # values like `0` or `False` in `target_field` are NOT discarded.
        if value is None:
            return True
        if isinstance(value, str):
            return value.strip() == ""
        return False
    
    
    def _is_usable_key(value: Any) -> bool:
        """Return True for a valid `ref_id` or page token (non-bool int or non-blank str)."""
        # Reject bool BEFORE checking int: in Python `bool` subclasses `int`, and
        # `True == 1` / `False == 0` would collide with integer keys in dicts/sets!
        if isinstance(value, bool):
            return False
        if isinstance(value, int):
            return True
        if isinstance(value, str):
            return value.strip() != ""
        # Lists and dicts are unhashable and cannot serve as join keys.
        return False
    
    
    def _is_valid_next_page(value: Any) -> bool:
        """Return True when `next_page` is a positive page number or non-blank cursor string."""
        if not _is_usable_key(value):
            return False
        # Pagination starts at page 1, so 0 or negative integers mean "no next page".
        if isinstance(value, int) and value < 1:
            return False
        return True
    
    
    def fetch_all_records(url: str, fetch_json: FetchJson) -> List[Dict[str, Any]]:
        """Fetch every page from `url` and return all dict records in page order."""
        # records: flat list of validated record dicts, e.g. [{"id": 101, "ref_id": "sku-9"}]
        records: List[Dict[str, Any]] = []
        # seen_pages: set of page tokens already requested, e.g. {1, 2}, to stop cycles
        seen_pages = set()
        current_page: Any = 1
    
        while True:
            seen_pages.add(current_page)
            body = fetch_json(url, {"page": current_page})
            if not isinstance(body, dict):
                # Null or non-object JSON payload: nothing readable and no next_page link.
                break
    
            # Extract valid dict items even if `data` is missing, null, or contains junk;
            # do NOT break when `data` is empty because a later page may still hold records.
            data = body.get("data")
            if isinstance(data, list):
                for item in data:
                    if isinstance(item, dict):
                        records.append(item)
    
            next_page = body.get("next_page")
            if not _is_valid_next_page(next_page) or next_page in seen_pages:
                # Stop at the end of pagination (`null`/missing) or on a repeated page bug.
                break
            current_page = next_page
    
        return records
    
    
    def get_enriched_records(api_a_url: str, api_b_url: str,
                             fetch_json: Optional[FetchJson] = None) -> List[Dict[str, Any]]:
        if fetch_json is None:
            fetch_json = http_get_json
    
        # Phase 1: Retrieve all record dicts across all pages from both endpoints.
        a_records = fetch_all_records(api_a_url, fetch_json)
        b_records = fetch_all_records(api_b_url, fetch_json)
    
        # Phase 2: Index API B once for O(1) average lookup.
        # value_by_ref: dict mapping usable ref_id -> first non-blank target_field,
        # e.g. {"sku-4": "warehouse-west", "sku-9": "warehouse-east"}.
        value_by_ref: Dict[Any, Any] = {}
        for record in b_records:
            ref_id = record.get("ref_id")
            target_value = record.get("target_field")
            if not _is_usable_key(ref_id) or _is_blank(target_value):
                continue
            # Keep the first usable match in B so later duplicates do not overwrite it.
            if ref_id not in value_by_ref:
                value_by_ref[ref_id] = target_value
    
        # Phase 3: Walk API A in its original order and emit joined records.
        # enriched: list of {"id": <id>, "target_field": <value>} in API A's order.
        enriched: List[Dict[str, Any]] = []
        for record in a_records:
            ref_id = record.get("ref_id")
            if not _is_usable_key(ref_id) or ref_id not in value_by_ref:
                continue
            record_id = record.get("id")
            if record_id is None:
                # Cannot form {"id": <id>, ...} when the source record has no id.
                continue
            enriched.append({
                "id": record_id,
                "target_field": value_by_ref[ref_id],
            })
    
        return enriched
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of joining two paginated APIs (endpoints that split large result lists into numbered pages, each carrying a "next_page" pointer to the next chunk) like matching a multi-page student roster (API A) against a multi-page locker directory (API B). First, you flip through every page of the locker directory and jot down a clean lookup sheet (ref_id -> target_field), crossing out torn or blank lines as you go. Then you walk down the student roster from page 1 to the end in exact order, looking up each student's ref_id on your sheet in one instant glance (hash join — indexing one dataset in a hash table so every record in the other dataset matches in O(1) average time).

Why do naive implementations break? First, scanning all of API B inside a nested loop for every API A record takes O(A * B) work (100,000,000 checks for 10,000 items per side). Second, trusting external JSON blindly crashes immediately: record["ref_id"] raises KeyError on a missing field, ref_id = ["sku-9"] raises TypeError as an unhashable list key, if not target_field: wrongly throws away valid values like 0, and a buggy "next_page": 1 loops forever without a visited-page set!

Let's trace Example 1 across pages:

API A: page 1 [{"id": 101, "ref_id": "sku-9"}, {"id": 102, "ref_id": "sku-4"}], next_page=2
       page 2 [{"id": 103, "ref_id": "sku-7"}],                                 next_page=null
API B: page 1 [{"ref_id": "sku-4", "target_field": "warehouse-west"}],          next_page=2
       page 2 [{"ref_id": "sku-9", "target_field": "warehouse-east"}],          next_page=null

1. Index B across both pages:
   value_by_ref = {"sku-4": "warehouse-west", "sku-9": "warehouse-east"}
2. Walk A in A's order:
   - id 101 ("sku-9") -> "warehouse-east" (kept first!)
   - id 102 ("sku-4") -> "warehouse-west" (kept second!)
   - id 103 ("sku-7") -> missing in B     (skipped)
Result: [{"id": 101, "target_field": "warehouse-east"}, {"id": 102, "target_field": "warehouse-west"}]

Complexity

Let A and B be the total number of items returned across P_A and P_B pages from api_a_url and api_b_url.

  • Time: O(A + B) local CPU work plus P_A + P_B sequential HTTP requests. We visit each page once (checking seen_pages in O(1) average time), inspect each of the B records once to populate the value_by_ref dictionary (O(1) average insertion per record), and scan each of the A records once in order (O(1) average dictionary lookup per record). In production, wall-clock latency is dominated by the P_A + P_B network round trips.
  • Space: O(A + B + P_A + P_B). a_records and b_records hold up to A and B record dicts, value_by_ref holds at most B distinct keys, seen_pages holds at most max(P_A, P_B) page tokens at a time, and enriched holds at most A output dicts. (If memory for A is tight, you can index API B first and stream API A one page at a time without storing a_records, reducing extra working memory to O(B) plus one page.)

Edge cases

  • End-of-pagination and malformed next_page values: null, missing "next_page", "", " ", False, 0, negative integers, or non-scalar values like [2] all terminate pagination cleanly.
  • Pagination cycles: If a buggy server returns "next_page": 1 on page 2, next_page in seen_pages stops immediately instead of spinning in an infinite HTTP loop.
  • Empty intermediate pages ("data": [] with "next_page": 3): Treated as zero records on that page while still advancing to page 3.
  • Malformed JSON bodies or items: A null page body stops pagination safely; "data": null or "data": "not a list" yields zero items for that page; non-dict items inside "data" (None, numbers, strings) are ignored.
  • Falsy vs blank target_field: None, "", and " " are skipped, whereas 0, False, and strings with surrounding spaces like " v6 " are preserved unaltered.
  • Unhashable or boolean ref_id values: Lists/dicts (["sku-9"]) are rejected before touching value_by_ref, and booleans (True/False) are explicitly rejected before isinstance(..., int) so Python's True == 1 / False == 0 rule cannot cause cross-type key collisions.
  • Duplicate ref_ids: Multiple A records sharing a ref_id are all enriched in A's order; multiple B records sharing a ref_id keep the first non-blank target_field.

Common mistakes

  • Stopping pagination as soon as "data" is empty: An API that filters records server-side after slicing pages often returns an empty "data": [] page in the middle with "next_page": 2; only stop when "next_page" itself is absent or invalid.
  • Indexing with body["data"] or record["ref_id"] instead of .get(...): A single missing key raises KeyError and aborts the entire pipeline.
  • Using if not value: to detect blank strings: In Python, bool(0) is False, so if not target_field: silently deletes valid numeric 0 values.
  • Forgetting bool subclasses int in Python: isinstance(False, (str, int)) is True! Without rejecting bool first, "next_page": false sends ?page=False, and "ref_id": true overwrites or matches "ref_id": 1.
  • Iterating over value_by_ref instead of a_records to build the output: That outputs records in API B's order and collapses duplicate ref_id rows from API A.
  • Swallowing network exceptions (except Exception: return []): Turning a 503 Service Unavailable on page 3 into an empty list corrupts downstream data silently; let transport errors fail loudly (or retry transient ones explicitly).

Follow-up questions

  • How would you handle transient network errors and HTTP 429 rate limits when fetching pages? Because fetching a page via GET is idempotent (repeating the exact same request has no side effects), wrap fetch_json in a retry helper that retries only transient failures — timeouts, connection errors, HTTP 429 Too Many Requests, and 5xx server errors — while failing immediately on permanent 4xx client errors like 401 or 404. Use exponential backoff (doubling the wait on each retry, e.g., 0.5s, 1s, 2s) with random jitter (a small random offset so hundreds of clients do not retry at the exact same millisecond), and respect any Retry-After response header on 429 responses.
  • What anomalies can happen if records are inserted or deleted on the server mid-pagination, and how can you prevent them? Numbered page pagination (page=1, 2, 3) is not an atomic snapshot: if a new item is inserted at the front of API A after you read page 1, the last item of page 1 shifts onto page 2 (producing a duplicate), whereas a deletion shifts page 2's first item backward into page 1 (skipping it completely). Switching the server to cursor (keyset) pagination — where "next_page" is an opaque bookmark like "after_id=1050" — anchors each page to the last seen item and eliminates shift bugs; if you cannot change the server, deduplicate API A records client-side using a seen_ids set.
  • How would you reduce wall-clock latency and peak RAM usage if both endpoints spanned tens of thousands of pages? First, fetch API A and API B concurrently (concurrent.futures.ThreadPoolExecutor or asyncio) since the two endpoints are independent; if an endpoint also reports total_pages, fetch pages in bounded parallel batches (say 8–16 in-flight requests to respect rate limits) and reassemble pages by page number so API A's order stays intact. Second, if API B is too huge to fit value_by_ref in RAM, either query API B selectively by batching A's ref_ids (?ref_ids=sku-9,sku-4,...) if supported, or spill value_by_ref into an indexed local SQLite table on disk and stream API A one page at a time.

Follow-up questions

Similar questions

More Armada interview questions

All 1 Armada questions →