Paginated API Fetching and Data Merging
Arrays & HashingModel answerLast 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
GETquery parameters formatted as?page=Nstarting from page 1. - Termination: When
next_pageisnullor 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
- Request all pages from both
api_a_urlandapi_b_url. - Perform an inner join between the dataset from API A and API B matching on the
ref_idattribute. - Return a list of output objects formatted as:
[{"id": <id>, "target_field": <value>}, ...] - Retain the exact order of elements as they appeared in API A.
- Omit a record if any of the following apply:
ref_idis missing orNone.id(from API A) is missing orNone.- No matching
ref_idexists in the dataset collected from API B. - The associated
target_fieldin API B isNone, an empty string"", or contains only whitespace characters.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Walkthrough
To solve this problem effectively, we must divide our responsibilities into clear sub-tasks:
- Paginated Data Retrieval: Abstract the pagination logic into a resilient helper function/generator.
- Defensive Field Validation: Safely extract values without triggering
KeyErrororAttributeErrorexceptions, while verifying validity rules (e.g., handling whitespace strings vs. numerical zeros). - Optimized Record Joining: Build an $O(1)$ hash map lookup table from API B first, then stream records from API A to preserve their original sequence.
1. Designing the Paginated Ingestion Helper
A common pitfall with pagination is getting stuck in infinite loops due to broken upstream APIs (e.g., next_page pointing back to page 1). To counter this, we can maintain a seen_pages set.
Our helper iterates using GET ?page=N, yields valid record dictionaries, extracts next_page, and terminates when next_page is None, missing, or already visited.
2. Defensive Validation
JSON data in production frequently contains anomalies. We must safely check:
- Is the JSON root a dictionary?
- Is the
"data"field a list? - Is each element inside
"data"a dictionary? - Is
target_fieldnon-empty? A string like" "must be discarded using.strip(), but non-string truthy/falsy values (e.g.,0,False) should be preserved if they occur.
3. Efficient Joining & Order Preservation
A naive nested-loop match between dataset A (size $N$) and dataset B (size $M$) would run in $O(N \times M)$ time complexity.
Instead:
- Read all pages from API B and populate a dictionary:
lookup[ref_id] = target_field. If duplicate validref_identries appear in API B, we can keep the first valid occurrence usingdict.setdefault(). - Iterate through API A page by page. For each valid record, check if its
ref_idis present inlookup. If found, construct the output record and append it to our result list.
Python 3 Implementation
import requests
from typing import Iterator, Dict, Any, List, Optional
def _fetch_all_records(url: str, timeout: int = 10, max_pages: int = 1000) -> Iterator[Dict[str, Any]]:
"""
Generator that fetches all pages from a paginated API endpoint
and yields individual record dictionaries.
"""
current_page: Optional[int] = 1
visited_pages = set()
while current_page is not None and current_page not in visited_pages and len(visited_pages) < max_pages:
visited_pages.add(current_page)
try:
response = requests.get(url, params={"page": current_page}, timeout=timeout)
response.raise_for_status()
payload = response.json()
except (requests.RequestException, ValueError):
# Handle HTTP errors or invalid JSON gracefully by stopping pagination
break
if not isinstance(payload, dict):
break
# Process the data array defensively
records = payload.get("data")
if isinstance(records, list):
for item in records:
if isinstance(item, dict):
yield item
# Determine next page pointer
next_page = payload.get("next_page")
if isinstance(next_page, int):
current_page = next_page
else:
current_page = None
def _is_valid_target(value: Any) -> bool:
"""Checks if target_field is present and not empty or whitespace-only."""
if value is None:
return False
if isinstance(value, str) and not value.strip():
return False
return True
def get_enriched_records(api_a_url: str, api_b_url: str) -> List[Dict[str, Any]]:
"""
Fetches paginated records from API A and API B, joins them on `ref_id`,
and returns enriched records preserving the order of API A.
"""
# 1. Build lookup dictionary from API B: ref_id -> target_field
ref_to_target: Dict[Any, Any] = {}
for record in _fetch_all_records(api_b_url):
ref_id = record.get("ref_id")
target_field = record.get("target_field")
if ref_id is None or not _is_valid_target(target_field):
continue
# Keep the first valid mapping encountered
ref_to_target.setdefault(ref_id, target_field)
# 2. Stream API A and construct enriched output list in original sequence
enriched_results: List[Dict[str, Any]] = []
for record in _fetch_all_records(api_a_url):
record_id = record.get("id")
ref_id = record.get("ref_id")
if record_id is None or ref_id is None:
continue
if ref_id in ref_to_target:
enriched_results.append({
"id": record_id,
"target_field": ref_to_target[ref_id]
})
return enriched_results
Complexity Analysis
-
Time Complexity:
- Fetching and parsing API B: $O(M)$ where $M$ is the total number of records across all pages of API B.
- Fetching and parsing API A: $O(N)$ where $N$ is the total number of records across all pages of API A.
- Hash map insertions and lookups operate in $O(1)$ average time.
- Overall Time Complexity: $O(N + M)$ time (excluding network latency).
-
Space Complexity:
- Storing the API B lookup map: $O(U)$ where $U \le M$ is the count of unique valid
ref_idkeys. - Storing the output list: $O(K)$ where $K \le N$ is the number of matched records.
- Overall Space Complexity: $O(M + N)$ auxiliary memory.
- Storing the API B lookup map: $O(U)$ where $U \le M$ is the count of unique valid