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 HTTPGETrequest withparamsencoded as query parameters onurl(handling URLs that may already contain?), decodes the UTF-8 JSON payload, and lets transport or non-2xxHTTP 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. Whenfetch_jsonis omitted orNone, usehttp_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_urlhas"id"and"ref_id". - Each valid record from
api_b_urlhas"ref_id"and"target_field".
Your implementation must satisfy these exact rules:
- Full pagination: Traverse all reachable pages from
api_a_urlandapi_b_url(including across empty intermediate"data": []pages when"next_page"still advances). - Order preservation: Emit output dictionaries in the exact record order returned by
api_a_url. Ifapi_a_urlcontains multiple records with the same"ref_id", enrich each qualifying record. - First usable match in
api_b_url: Ifapi_b_urlcontains multiple records with the same"ref_id", use the first one whose"target_field"is valid. - Filtering invalid records and blank values: Skip a record when:
"id"is missing ornullon theapi_a_urlrecord;"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 inapi_b_url; "target_field"is missing,null,"", or whitespace-only (keep non-string falsy values such as0orFalse, and preserve non-empty strings without stripping their padding).
- Defensive payload handling: Never crash on missing dictionary keys,
nullpage 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_urlresponses:- 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}
- Page
api_b_urlresponses:- 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}
- Page
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_urlresponses:- 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}
- Page
api_b_urlresponses:- 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}
- Page
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 thanO(A * B).
Step-by-step walkthrough
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_urlandapi_b_url). We start each endpoint atpage=1and keep following"next_page"until"next_page"isnull, 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/Noneor 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
0orFalsein"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.
- Skip any record that is not a JSON object (
- Input: Two paginated HTTP endpoints (
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_jsonimplementation, Python's built-inurllib.request.urlopenhandles GET requests cleanly: - Ifurlalready contains a?(for examplehttps://host/items?env=prod), we glueurlencode(params)on with"&"; otherwise we use"?". - We settimeout=10so an unresponsive server cannot hang the process forever. - We intentionally let HTTP4xx/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"))Write explicit validation helpers for values, keys, and page tokens
Messy JSON payloads trip up careless Python checks in three classic ways:
if not value:drops0: Writingif not target_field:treatstarget_field = 0as blank. Instead,_is_blank(value)checks specifically forNoneand strings that become""after.strip().boolis a subclass ofintin Python:isinstance(True, int)evaluates toTrue, andTrue == 1/False == 0in Python dictionaries! Checkingisinstance(value, bool)first inside_is_usable_keyensures"ref_id": truenever collides with"ref_id": 1, and"next_page": falsenever triggers?page=False.- Unhashable JSON types and invalid page numbers: A malformed
"ref_id": ["sku-9"]is alistand would crash withTypeError: unhashable type: 'list'on dict lookup. Accepting only non-boolintand non-blankstrmakes every accepted key safe to hash, and_is_valid_next_pageadditionally 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 TruePaginate defensively with cycle protection
Both endpoints share the exact same envelope shape (
{"data": [...], "next_page": ...}), so onefetch_all_recordshelper handles both APIs.Walk through what can go wrong on any page response and how the loop handles each case: -
bodyisNoneor not adict: We cannot read"data"or"next_page", sobreak. -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": 3still points to more data! - An element inside"data"isNone,7, or"junk": Only append items whereisinstance(item, dict). - Buggy server returns a cycle (page 1 -> 2 -> 1): Aseen_pagesset records every page token we have already requested and stops immediately ifnext_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 recordsIndex API B in a dictionary and join in API A's order
If API A has
arecords and API B hasbrecords, scanning all ofb_recordsfor each record ina_recordstakesO(a * b)time (10,000 * 10,000 = 100,000,000checks). Instead, we perform an in-memory hash join:- Build
value_by_reffromb_recordsin oneO(b)pass: Map each validref_idto its first non-blanktarget_field. - Scan
a_recordsin oneO(a)pass: Look up each A record'sref_idinvalue_by_refinO(1)average time. Because we iterate overa_records(and never overvalue_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"}]- Build
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 plusP_A + P_Bsequential HTTP requests. We visit each page once (checkingseen_pagesinO(1)average time), inspect each of theBrecords once to populate thevalue_by_refdictionary (O(1)average insertion per record), and scan each of theArecords once in order (O(1)average dictionary lookup per record). In production, wall-clock latency is dominated by theP_A + P_Bnetwork round trips. - Space:
O(A + B + P_A + P_B).a_recordsandb_recordshold up toAandBrecord dicts,value_by_refholds at mostBdistinct keys,seen_pagesholds at mostmax(P_A, P_B)page tokens at a time, andenrichedholds at mostAoutput dicts. (If memory forAis tight, you can index API B first and stream API A one page at a time without storinga_records, reducing extra working memory toO(B)plus one page.)
Edge cases
- End-of-pagination and malformed
next_pagevalues: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": 1on page 2,next_page in seen_pagesstops 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
nullpage body stops pagination safely;"data": nullor"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, whereas0,False, and strings with surrounding spaces like" v6 "are preserved unaltered. - Unhashable or boolean
ref_idvalues: Lists/dicts (["sku-9"]) are rejected before touchingvalue_by_ref, and booleans (True/False) are explicitly rejected beforeisinstance(..., int)so Python'sTrue == 1/False == 0rule cannot cause cross-type key collisions. - Duplicate
ref_ids: Multiple A records sharing aref_idare all enriched in A's order; multiple B records sharing aref_idkeep the first non-blanktarget_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"]orrecord["ref_id"]instead of.get(...): A single missing key raisesKeyErrorand aborts the entire pipeline. - Using
if not value:to detect blank strings: In Python,bool(0)isFalse, soif not target_field:silently deletes valid numeric0values. - Forgetting
boolsubclassesintin Python:isinstance(False, (str, int))isTrue! Without rejectingboolfirst,"next_page": falsesends?page=False, and"ref_id": trueoverwrites or matches"ref_id": 1. - Iterating over
value_by_refinstead ofa_recordsto build the output: That outputs records in API B's order and collapses duplicateref_idrows from API A. - Swallowing network exceptions (
except Exception: return []): Turning a503 Service Unavailableon 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
GETis idempotent (repeating the exact same request has no side effects), wrapfetch_jsonin a retry helper that retries only transient failures — timeouts, connection errors, HTTP429 Too Many Requests, and5xxserver errors — while failing immediately on permanent4xxclient errors like401or404. 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 anyRetry-Afterresponse header on429responses. - 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 aseen_idsset. - 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.ThreadPoolExecutororasyncio) since the two endpoints are independent; if an endpoint also reportstotal_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 fitvalue_by_refin RAM, either query API B selectively by batching A'sref_ids (?ref_ids=sku-9,sku-4,...) if supported, or spillvalue_by_refinto an indexed local SQLite table on disk and stream API A one page at a time.
Follow-up questions
- How would you handle transient network errors and HTTP 429 rate limits when fetching pages?
- What anomalies can happen if records are inserted or deleted on the server mid-pagination, and how can you prevent them?
- How would you reduce wall-clock latency and peak RAM usage if both endpoints spanned tens of thousands of pages?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array