Unified User Model and Mappers for Heterogeneous API Payloads
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Your service ingests person records from multiple upstream directory APIs that represent the same domain entity using conflicting JSON shapes: field names vary, some providers nest name or contact objects, record IDs arrive as integers in one API and strings in another, creation timestamps appear as ISO 8601 strings or numeric Unix epoch seconds, and active status is encoded either as a word or as a boolean flag.
Design a canonical User data model and per-provider boundary mappers so downstream code can consume every record uniformly:
NormalizationError(ValueError)— Raised when a payload is not adict, a source name is unknown, a required field is missing/None, or any present field has an unexpected type or format.EmailAddress(address: str, kind: Optional[str] = None, primary: bool = False)— Normalized representation of one email entry.Userdataclass fields and properties:source: str("api_a"or"api_b"),source_id: str(non-empty trimmed string), andcreated_at: datetime(timezone-awaredatetimeconverted to UTC).- Optional fields defaulting to empty/missing:
first_name: Optional[str] = None,last_name: Optional[str] = None,emails: List[EmailAddress] = field(default_factory=list),is_active: Optional[bool] = None,phone: Optional[str] = None,time_zone: Optional[str] = None, andextras: Dict[str, Any] = field(default_factory=dict)holding any top-level payload keys not consumed by that provider's mapper. user.key -> str— Returns"<source>:<source_id>"so identical IDs from separate providers never collide.user.primary_email -> Optional[str]— Returns the first email address withprimary=True, falling back toemails[0].addresswhen none is flagged primary, orNonewhenemailsis empty.
from_api_a(payload: Dict[str, Any]) -> User— Maps"api_a"objects (id,first_name,last_name,email,created,status,phone). Requiresidandcreated. Non-emptyemailbecomes a singleEmailAddress(..., kind=None, primary=True).statusmaps"active"toTrueand"inactive"toFalse(case-insensitively, ignoring surrounding whitespace), orNonewhen absent/None.from_api_b(payload: Dict[str, Any]) -> User— Maps"api_b"objects (userId,namewith{given, family},emailslist of{type, value, primary},createdAt,isActive,timezone). RequiresuserIdandcreatedAt. Email items missing a non-blank"value"are skipped.normalize(source: str, payload: Any) -> User— Dispatches"api_a"and"api_b"to their mappers, raisingNormalizationErrorfor unknown sources or non-dictionary payloads.
Examples
Example 1
Input:
source = "api_a"
payload = {
"id": 4815,
"first_name": "Devon",
"last_name": "Patel",
"email": "devon.patel@acme.io",
"created": "2024-09-15T14:20:00Z",
"status": "active",
"phone": "+1-415-555-0192",
}
Output:
User(
source="api_a",
source_id="4815",
created_at=datetime(2024, 9, 15, 14, 20, tzinfo=timezone.utc),
first_name="Devon",
last_name="Patel",
emails=[EmailAddress(address="devon.patel@acme.io", kind=None, primary=True)],
is_active=True,
phone="+1-415-555-0192",
time_zone=None,
extras={},
)
# user.key == "api_a:4815"
# user.primary_email == "devon.patel@acme.io"
Explanation: Integer id 4815 is converted to "4815", the UTC ISO 8601 string becomes a timezone-aware UTC datetime, "active" maps to True, and the flat email string is wrapped as a single primary EmailAddress.
Example 2
Input:
source = "api_b"
payload = {
"userId": "usr_77b4",
"name": {"given": "Devon", "family": "Patel"},
"emails": [
{"type": "personal", "value": "devon@patel.dev", "primary": False},
{"type": "work", "value": "devon.patel@acme.io", "primary": True},
],
"createdAt": 1726410000,
"isActive": False,
"timezone": "Europe/London",
"tier": "enterprise",
}
Output:
User(
source="api_b",
source_id="usr_77b4",
created_at=datetime(2024, 9, 15, 14, 20, tzinfo=timezone.utc),
first_name="Devon",
last_name="Patel",
emails=[
EmailAddress(address="devon@patel.dev", kind="personal", primary=False),
EmailAddress(address="devon.patel@acme.io", kind="work", primary=True),
],
is_active=False,
phone=None,
time_zone="Europe/London",
extras={"tier": "enterprise"},
)
# user.key == "api_b:usr_77b4"
# user.primary_email == "devon.patel@acme.io"
Explanation: Nested name fields flatten into first_name and last_name, Unix epoch 1726410000 resolves to 2024-09-15 14:20:00+00:00 in UTC, primary_email picks the second entry because it has primary=True, isActive=False is preserved as False, and the unmapped "tier" field is retained in extras.
Constraints
- Record IDs (
id/userId) acceptint(excludingbool) or non-emptystr(surrounding whitespace trimmed);None, booleans, floats, and blank strings raiseNormalizationError. - Creation timestamps (
created/createdAt) acceptint/floatUnix seconds (excludingbooland out-of-range values such as raw milliseconds) or ISO 8601 strings carrying an explicit UTC offset (Z,z, or±HH:MM); naive timestamp strings without an offset raiseNormalizationError. - Optional string fields strip surrounding whitespace and normalize empty/whitespace-only strings to
None; non-string values where strings are expected raiseNormalizationError. - Boolean fields (
isActive,emails[].primary) acceptboolorNoneonly; strings like"true"or integers like1raiseNormalizationError.
Step-by-step walkthrough
Clarify requirements and establish normalization rules
Both sample payloads describe a person named Devon Patel using incompatible field names, nesting levels, ID types, and timestamp encodings. Our goal is to design one canonical
Userclass that models a person cleanly, paired with one boundary mapper per upstream API so downstream application logic never checks which provider produced a record.Before writing code, pin down the boundary rules explicitly:
- Entity vs. sub-records: Both payloads represent a
User. Because"api_b"supplies multiple email entries with metadata (type,primary), each email belongs in a smallEmailAddresssub-class rather than discarding secondary addresses. - Required vs. optional fields: Every record must supply an upstream ID and creation timestamp (
id/userIdandcreated/createdAt) so records can be uniquely identified and ordered; all other attributes (first_name,last_name,emails,is_active,phone,time_zone) are optional. - Missing vs. malformed values: A missing optional field defaults to
None(or an empty list). A present field carrying the wrong type or an unrecognized token (such asstatus: "suspended"orid: True) raisesNormalizationErrorimmediately so upstream schema changes surface early instead of corrupting stored rows. - Preventing cross-provider ID collisions:
"api_a"may emitid = 19while"api_b"emitsuserId = "19"for a completely unrelated user, so a record's composite key combines source and ID:"api_a:19"vs"api_b:19". - Preserving unmapped fields: Unrecognized top-level keys (like
"tier": "enterprise"in Example 2) land in anextrasdictionary so newly added provider fields are never silently dropped.
- Entity vs. sub-records: Both payloads represent a
Group every field into shared, optional, or source-specific
Line up both sample payloads in a mapping table and classify each concept as shared (carried by both APIs in different shapes), optional (supplied by only one API), or source-specific (unrecognized top-level keys):
Concept API A (Example 1) API B (Example 2) Group User field & type ------------ -------------------------- -------------------------------- -------- ------------------------- Identity id: 4815 (int) userId: "usr_77b4" (str) shared source + source_id: str Person name first_name, last_name name: {given, family} (nested) shared first_name, last_name Emails email: "devon.patel@..." emails: [{type, value, primary}] shared emails: List[EmailAddress] Created time "2024-09-15T14:20:00Z" 1726410000 (int) shared created_at: datetime (UTC) Active state status: "active" isActive: false shared is_active: Optional[bool] Phone "+1-415-555-0192" (absent) optional phone: Optional[str] Time zone (absent) timezone: "Europe/London" optional time_zone: Optional[str] Other keys (none) tier: "enterprise" specific extras: Dict[str, Any]Notice why each target type wins:
strforsource_id: Every integer (4815) converts losslessly to"4815", whereas"usr_77b4"cannot be represented as anint.- Timezone-aware
datetimein UTC forcreated_at:"api_a"uses ISO 8601 ("2024-09-15T14:20:00Z", where"Z"denotes UTC, Coordinated Universal Time at zero offset), while"api_b"uses a Unix timestamp (seconds elapsed since1970-01-01T00:00:00Z). Converting both to UTCdatetimelets us compare and sort records directly. Here both samples encode the exact same instant:19,981 days * 86,400 s/day + 14 h 20 m * 60 s/m = 1,726,358,400 + 51,600 = 1,726,410,000. List[EmailAddress]foremails: A single email string fits cleanly into a one-element list, whereas collapsing two emails into a single string loses metadata.Optional[bool]foris_active: Two-state words ("active"/"inactive") and booleans (true/false) express the exact same flag, whileNonedistinguishes "omitted" fromFalse.
Define the common User and EmailAddress data classes
Python's
@dataclassprovides clean, typed value objects using only the standard library. Put required fields first, default optional scalar fields toNone, and usefield(default_factory=list)/field(default_factory=dict)for mutable containers so eachUserinstance owns fresh collections. Implementkeyandprimary_emailas@propertygetters so derived attributes stay automatically synchronized with underlying fields:from typing import Any, Callable, Dict, List, Optional from dataclasses import dataclass, field from datetime import datetime, timezone class NormalizationError(ValueError): """A payload is missing a required field or holds a value in an unexpected format.""" @dataclass class EmailAddress: address: str kind: Optional[str] = None # e.g. "work" or "personal" when supplied by the source primary: bool = False @dataclass class User: """Normalized representation of a user record regardless of which upstream API produced it.""" source: str # upstream API identifier, e.g. "api_a" or "api_b" source_id: str # upstream record ID normalized to a non-empty string created_at: datetime # timezone-aware creation timestamp normalized to UTC first_name: Optional[str] = None last_name: Optional[str] = None emails: List[EmailAddress] = field(default_factory=list) is_active: Optional[bool] = None # None means the upstream payload omitted active status phone: Optional[str] = None time_zone: Optional[str] = None # IANA timezone string such as "Europe/London" # extras: dict of top-level source fields not consumed by the mapper, e.g. {"tier": "enterprise"} extras: Dict[str, Any] = field(default_factory=dict) @property def key(self) -> str: """Composite key '<source>:<source_id>' so IDs from different APIs never collide.""" return f"{self.source}:{self.source_id}" @property def primary_email(self) -> Optional[str]: """Return the first email marked primary, else the first email in list order, else None.""" for email in self.emails: if email.primary: return email.address if self.emails: return self.emails[0].address return NoneBuild small validation and conversion helpers at the boundary
Convert every raw value at the ingestion boundary — before constructing
User— using small shared helpers so every mapper enforces identical rules:_requirechecksvalue is None, neverif not value: Unix timestamp0(1970-01-01T00:00:00Z) andisActive = False(as in Example 2) are falsy in Python yet completely valid!_to_idand_to_utccheckisinstance(value, bool)first: In Python,boolsubclassesint(isinstance(True, int)isTrue). Rejectingboolfirst preventsid: Truefrom turning into"True"orcreatedAt: Truefrom turning into1970-01-01T00:00:01Z._to_utcrejects ambiguous or wrong-unit timestamps: An ISO string lacking a timezone offset ("2024-09-15T14:20:00") is rejected because its local timezone is unknown, and a millisecond Unix timestamp (1726410000000) passed where seconds were expected overflows past year9999and raisesNormalizationError.
def _check_dict(payload: Any, source: str) -> Dict[str, Any]: if not isinstance(payload, dict): raise NormalizationError(f"{source}: payload should be a JSON object") return payload def _require(payload: Dict[str, Any], name: str, source: str) -> Any: value = payload.get(name) # Check 'is None' rather than 'not value' so valid falsy values like 0 or False survive if value is None: raise NormalizationError(f"{source}: missing required field {name!r}") return value def _to_id(value: Any, source: str) -> str: # In Python bool subclasses int (isinstance(True, int) is True), so reject bool first if isinstance(value, bool): raise NormalizationError(f"{source}: bad id {value!r}") if isinstance(value, int): return str(value) if isinstance(value, str): cleaned = value.strip() if cleaned: return cleaned raise NormalizationError(f"{source}: bad id {value!r}") def _to_utc(value: Any, source: str) -> datetime: """Convert Unix seconds (int/float) or an offset-bearing ISO 8601 string to a UTC datetime.""" if isinstance(value, bool): raise NormalizationError(f"{source}: bad timestamp {value!r}") if isinstance(value, (int, float)): try: return datetime.fromtimestamp(value, tz=timezone.utc) except (OverflowError, OSError, ValueError): # Millisecond timestamps passed as seconds land past year 9999 and raise here raise NormalizationError(f"{source}: timestamp out of range {value!r}") from None if isinstance(value, str): text = value.strip() # Replace trailing Z/z with +00:00 so fromisoformat works on all Python 3 versions if text.endswith(("Z", "z")): text = text[:-1] + "+00:00" try: parsed = datetime.fromisoformat(text) except ValueError: raise NormalizationError(f"{source}: bad timestamp {value!r}") from None # Reject naive timestamps without a timezone offset because local time is ambiguous if parsed.tzinfo is None: raise NormalizationError(f"{source}: timestamp {value!r} has no UTC offset") return parsed.astimezone(timezone.utc) raise NormalizationError(f"{source}: bad timestamp {value!r}") def _optional_str(value: Any, name: str, source: str) -> Optional[str]: """Convert missing or whitespace-only strings to None; reject non-string types.""" if value is None: return None if not isinstance(value, str): raise NormalizationError(f"{source}: {name} should be a string, got {value!r}") cleaned = value.strip() if not cleaned: return None return cleaned def _optional_bool(value: Any, name: str, source: str) -> Optional[bool]: if value is None: return None if not isinstance(value, bool): raise NormalizationError(f"{source}: {name} should be true or false, got {value!r}") return value def _unmapped(payload: Dict[str, Any], known_fields: set) -> Dict[str, Any]: """Preserve top-level fields not explicitly mapped so new upstream fields are not lost.""" extras: Dict[str, Any] = {} for name, value in payload.items(): if name not in known_fields: extras[name] = value return extrasWrite the per-API mappers for API A and API B
With the boundary helpers ready, each provider's mapper stays flat and self-contained:
from_api_awraps a non-emptyemailstring into[EmailAddress(..., primary=True)]and translates"active"/"inactive"(case-insensitively) via_A_ACTIVE_BY_STATUSso unexpected tokens like"suspended"raiseNormalizationError.from_api_bunpacks the optional nestednamedict ({"given": ..., "family": ...}), validates each entry inemails(skipping items whose"value"is missing or blank), and captures leftover top-level keys intoextras.
_A_FIELDS = {"id", "first_name", "last_name", "email", "created", "status", "phone"} _A_ACTIVE_BY_STATUS = {"active": True, "inactive": False} def _a_status(value: Any, source: str) -> Optional[bool]: if value is None: return None if isinstance(value, str): normalized_status = value.strip().lower() if normalized_status in _A_ACTIVE_BY_STATUS: return _A_ACTIVE_BY_STATUS[normalized_status] # Reject unexpected words like "suspended" instead of silently guessing False raise NormalizationError(f"{source}: unknown status {value!r}") def from_api_a(payload: Dict[str, Any]) -> User: source = "api_a" data = _check_dict(payload, source) raw_id = _require(data, "id", source) raw_created = _require(data, "created", source) source_id = _to_id(raw_id, source) created_at = _to_utc(raw_created, source) emails: List[EmailAddress] = [] single_email = _optional_str(data.get("email"), "email", source) if single_email is not None: emails.append(EmailAddress(address=single_email, primary=True)) return User( source=source, source_id=source_id, created_at=created_at, first_name=_optional_str(data.get("first_name"), "first_name", source), last_name=_optional_str(data.get("last_name"), "last_name", source), emails=emails, is_active=_a_status(data.get("status"), source), phone=_optional_str(data.get("phone"), "phone", source), extras=_unmapped(data, _A_FIELDS), ) _B_FIELDS = {"userId", "name", "emails", "createdAt", "isActive", "timezone"} def _b_emails(value: Any, source: str) -> List[EmailAddress]: if value is None: return [] if not isinstance(value, list): raise NormalizationError(f"{source}: emails should be a list, got {value!r}") emails: List[EmailAddress] = [] for item in value: if not isinstance(item, dict): raise NormalizationError(f"{source}: bad email entry {item!r}") address = _optional_str(item.get("value"), "emails[].value", source) if address is None: # Skip entries without a usable email string rather than storing empty addresses continue kind = _optional_str(item.get("type"), "emails[].type", source) primary_flag = _optional_bool(item.get("primary"), "emails[].primary", source) emails.append(EmailAddress(address=address, kind=kind, primary=primary_flag is True)) return emails def from_api_b(payload: Dict[str, Any]) -> User: source = "api_b" data = _check_dict(payload, source) raw_id = _require(data, "userId", source) raw_created = _require(data, "createdAt", source) source_id = _to_id(raw_id, source) created_at = _to_utc(raw_created, source) name_obj = data.get("name") if name_obj is None: name_obj = {} if not isinstance(name_obj, dict): raise NormalizationError(f"{source}: name should be an object, got {name_obj!r}") return User( source=source, source_id=source_id, created_at=created_at, first_name=_optional_str(name_obj.get("given"), "name.given", source), last_name=_optional_str(name_obj.get("family"), "name.family", source), emails=_b_emails(data.get("emails"), source), is_active=_optional_bool(data.get("isActive"), "isActive", source), time_zone=_optional_str(data.get("timezone"), "timezone", source), extras=_unmapped(data, _B_FIELDS), )Dispatch by source name and walk through Examples 1 and 2
Register each provider mapper in
MAPPERSsonormalize(source, payload)serves as a single entry point. Supporting"api_c"later requires only writingfrom_api_cand adding one dictionary line:MAPPERS: Dict[str, Callable[[Dict[str, Any]], User]] = { "api_a": from_api_a, "api_b": from_api_b, } def normalize(source: str, payload: Any) -> User: mapper = MAPPERS.get(source) if mapper is None: raise NormalizationError(f"no mapper for source {source!r}") data = _check_dict(payload, source) return mapper(data)Trace Example 1 and Example 2 side by side through
normalize:Normalized field normalize("api_a", Example 1) normalize("api_b", Example 2) ----------------- ------------------------------------- --------------------------------------------- key "api_a:4815" "api_b:usr_77b4" first_name "Devon" "Devon" last_name "Patel" "Patel" emails [EmailAddress("devon.patel@acme.io", [EmailAddress("devon@patel.dev", "personal", False), kind=None, primary=True)] EmailAddress("devon.patel@acme.io", "work", True)] primary_email "devon.patel@acme.io" "devon.patel@acme.io" created_at 2024-09-15 14:20:00+00:00 2024-09-15 14:20:00+00:00 is_active True False phone "+1-415-555-0192" None time_zone None "Europe/London" extras {} {"tier": "enterprise"}Complete Python solution
Putting the canonical data classes, boundary validators, provider mappers, and dispatcher together gives the complete
solution.py:from typing import Any, Callable, Dict, List, Optional from dataclasses import dataclass, field from datetime import datetime, timezone class NormalizationError(ValueError): """A payload is missing a required field or holds a value in an unexpected format.""" @dataclass class EmailAddress: address: str kind: Optional[str] = None # e.g. "work" or "personal" when supplied by the source primary: bool = False @dataclass class User: """Normalized representation of a user record regardless of which upstream API produced it.""" source: str # upstream API identifier, e.g. "api_a" or "api_b" source_id: str # upstream record ID normalized to a non-empty string created_at: datetime # timezone-aware creation timestamp normalized to UTC first_name: Optional[str] = None last_name: Optional[str] = None emails: List[EmailAddress] = field(default_factory=list) is_active: Optional[bool] = None # None means the upstream payload omitted active status phone: Optional[str] = None time_zone: Optional[str] = None # IANA timezone string such as "Europe/London" # extras: dict of top-level source fields not consumed by the mapper, e.g. {"tier": "enterprise"} extras: Dict[str, Any] = field(default_factory=dict) @property def key(self) -> str: """Composite key '<source>:<source_id>' so IDs from different APIs never collide.""" return f"{self.source}:{self.source_id}" @property def primary_email(self) -> Optional[str]: """Return the first email marked primary, else the first email in list order, else None.""" for email in self.emails: if email.primary: return email.address if self.emails: return self.emails[0].address return None # ----- Shared validation and conversion helpers used at the ingestion boundary ----- def _check_dict(payload: Any, source: str) -> Dict[str, Any]: if not isinstance(payload, dict): raise NormalizationError(f"{source}: payload should be a JSON object") return payload def _require(payload: Dict[str, Any], name: str, source: str) -> Any: value = payload.get(name) # Check 'is None' rather than 'not value' so valid falsy values like 0 or False survive if value is None: raise NormalizationError(f"{source}: missing required field {name!r}") return value def _to_id(value: Any, source: str) -> str: # In Python bool subclasses int (isinstance(True, int) is True), so reject bool first if isinstance(value, bool): raise NormalizationError(f"{source}: bad id {value!r}") if isinstance(value, int): return str(value) if isinstance(value, str): cleaned = value.strip() if cleaned: return cleaned raise NormalizationError(f"{source}: bad id {value!r}") def _to_utc(value: Any, source: str) -> datetime: """Convert Unix seconds (int/float) or an offset-bearing ISO 8601 string to a UTC datetime.""" if isinstance(value, bool): raise NormalizationError(f"{source}: bad timestamp {value!r}") if isinstance(value, (int, float)): try: return datetime.fromtimestamp(value, tz=timezone.utc) except (OverflowError, OSError, ValueError): # Millisecond timestamps passed as seconds land past year 9999 and raise here raise NormalizationError(f"{source}: timestamp out of range {value!r}") from None if isinstance(value, str): text = value.strip() # Replace trailing Z/z with +00:00 so fromisoformat works on all Python 3 versions if text.endswith(("Z", "z")): text = text[:-1] + "+00:00" try: parsed = datetime.fromisoformat(text) except ValueError: raise NormalizationError(f"{source}: bad timestamp {value!r}") from None # Reject naive timestamps without a timezone offset because local time is ambiguous if parsed.tzinfo is None: raise NormalizationError(f"{source}: timestamp {value!r} has no UTC offset") return parsed.astimezone(timezone.utc) raise NormalizationError(f"{source}: bad timestamp {value!r}") def _optional_str(value: Any, name: str, source: str) -> Optional[str]: """Convert missing or whitespace-only strings to None; reject non-string types.""" if value is None: return None if not isinstance(value, str): raise NormalizationError(f"{source}: {name} should be a string, got {value!r}") cleaned = value.strip() if not cleaned: return None return cleaned def _optional_bool(value: Any, name: str, source: str) -> Optional[bool]: if value is None: return None if not isinstance(value, bool): raise NormalizationError(f"{source}: {name} should be true or false, got {value!r}") return value def _unmapped(payload: Dict[str, Any], known_fields: set) -> Dict[str, Any]: """Preserve top-level fields not explicitly mapped so new upstream fields are not lost.""" extras: Dict[str, Any] = {} for name, value in payload.items(): if name not in known_fields: extras[name] = value return extras # ----- API A mapper: flat fields, integer id, ISO 8601 timestamp, status string ----- _A_FIELDS = {"id", "first_name", "last_name", "email", "created", "status", "phone"} _A_ACTIVE_BY_STATUS = {"active": True, "inactive": False} def _a_status(value: Any, source: str) -> Optional[bool]: if value is None: return None if isinstance(value, str): normalized_status = value.strip().lower() if normalized_status in _A_ACTIVE_BY_STATUS: return _A_ACTIVE_BY_STATUS[normalized_status] # Reject unexpected words like "suspended" instead of silently guessing False raise NormalizationError(f"{source}: unknown status {value!r}") def from_api_a(payload: Dict[str, Any]) -> User: source = "api_a" data = _check_dict(payload, source) raw_id = _require(data, "id", source) raw_created = _require(data, "created", source) source_id = _to_id(raw_id, source) created_at = _to_utc(raw_created, source) emails: List[EmailAddress] = [] single_email = _optional_str(data.get("email"), "email", source) if single_email is not None: emails.append(EmailAddress(address=single_email, primary=True)) return User( source=source, source_id=source_id, created_at=created_at, first_name=_optional_str(data.get("first_name"), "first_name", source), last_name=_optional_str(data.get("last_name"), "last_name", source), emails=emails, is_active=_a_status(data.get("status"), source), phone=_optional_str(data.get("phone"), "phone", source), extras=_unmapped(data, _A_FIELDS), ) # ----- API B mapper: string userId, nested name, emails list, Unix seconds, boolean flag ----- _B_FIELDS = {"userId", "name", "emails", "createdAt", "isActive", "timezone"} def _b_emails(value: Any, source: str) -> List[EmailAddress]: if value is None: return [] if not isinstance(value, list): raise NormalizationError(f"{source}: emails should be a list, got {value!r}") emails: List[EmailAddress] = [] for item in value: if not isinstance(item, dict): raise NormalizationError(f"{source}: bad email entry {item!r}") address = _optional_str(item.get("value"), "emails[].value", source) if address is None: # Skip entries without a usable email string rather than storing empty addresses continue kind = _optional_str(item.get("type"), "emails[].type", source) primary_flag = _optional_bool(item.get("primary"), "emails[].primary", source) emails.append(EmailAddress(address=address, kind=kind, primary=primary_flag is True)) return emails def from_api_b(payload: Dict[str, Any]) -> User: source = "api_b" data = _check_dict(payload, source) raw_id = _require(data, "userId", source) raw_created = _require(data, "createdAt", source) source_id = _to_id(raw_id, source) created_at = _to_utc(raw_created, source) name_obj = data.get("name") if name_obj is None: name_obj = {} if not isinstance(name_obj, dict): raise NormalizationError(f"{source}: name should be an object, got {name_obj!r}") return User( source=source, source_id=source_id, created_at=created_at, first_name=_optional_str(name_obj.get("given"), "name.given", source), last_name=_optional_str(name_obj.get("family"), "name.family", source), emails=_b_emails(data.get("emails"), source), is_active=_optional_bool(data.get("isActive"), "isActive", source), time_zone=_optional_str(data.get("timezone"), "timezone", source), extras=_unmapped(data, _B_FIELDS), ) # ----- Registry dispatch: adding a new API requires one mapper + one entry here ----- # MAPPERS: dict mapping source name -> mapper function converting raw dict to User MAPPERS: Dict[str, Callable[[Dict[str, Any]], User]] = { "api_a": from_api_a, "api_b": from_api_b, } def normalize(source: str, payload: Any) -> User: mapper = MAPPERS.get(source) if mapper is None: raise NormalizationError(f"no mapper for source {source!r}") data = _check_dict(payload, source) return mapper(data)✅ Submit now — all tests should pass.
Intuition & how it works
Think of an international airport customs desk where travelers arrive carrying passports from dozens of countries: one country prints dates as 2024-09-15T14:20:00Z, another uses numeric epoch seconds, one prints a single contact line, and another lists personal and work contacts separately. Instead of forcing every gate agent inside the terminal to memorize 50 passport layouts, customs translates each passport once at the border into a single standardized boarding pass.
Passing raw API dictionaries straight into application code fails for the exact same reason: if "userId" in data: checks, date parsers, and null guards spread across every feature and break whenever a new provider is added. Conversely, stuffing every API's raw property names (id, userId, status, isActive) side by side onto one giant class leaves callers guessing which attributes are populated. Modeling a canonical User entity and converting raw payloads at the ingestion boundary isolates every upstream quirk inside one small mapper per source.
Walk through how Examples 1 and 2 normalize conflicting shapes into identical Python types:
- Example 1 (
"api_a") arrives with"id": 4815,"created": "2024-09-15T14:20:00Z","status": "active", and"email": "devon.patel@acme.io".from_api_aconverts4815tosource_id = "4815"(key = "api_a:4815"), parses the ISO 8601 date string (a standard text timestamp format) into2024-09-15 14:20:00+00:00in UTC (Coordinated Universal Time), maps"active"tois_active = True, and wraps the email into[EmailAddress("devon.patel@acme.io", primary=True)]. - Example 2 (
"api_b") arrives with"userId": "usr_77b4","createdAt": 1726410000,"isActive": false, two nested email objects (with"work"markedprimary: truein the second slot), and"tier": "enterprise".from_api_bkeepssource_id = "usr_77b4"(key = "api_b:usr_77b4"), converts the Unix timestamp (1726410000seconds since1970-01-01T00:00:00Z) into the exact same2024-09-15 14:20:00+00:00UTCdatetime, preservesis_active = False, selects"devon.patel@acme.io"viauser.primary_email, and saves{"tier": "enterprise"}inextras. - Downstream callers read
user.primary_email,user.created_at, anduser.is_activeuniformly without ever branching on"api_a"vs"api_b".
Complexity
- Time: O(k + m) per payload (linear in payload size), where
kis the number of top-level keys in the JSON dictionary andmis the number of entries inemails. Each known field is looked up in O(1) dictionary time and validated once,_b_emailsscans thememail objects once, and_unmappediterates over thektop-level keys once. - Space: O(u + m) per payload, where
uis the number of unmapped top-level keys copied intoextrasandmis the number of normalizedEmailAddressobjects stored onUser. The mappers hold no cross-record state, so millions of records can be streamed in constant working memory.
Edge cases
- Valid falsy values (
0andFalse):createdAt = 0(1970-01-01T00:00:00Z) andisActive = False(Example 2) are valid values thatif not value:would mistakenly reject; checkingif value is None:preserves them. - Booleans masquerading as integers: In Python,
boolsubclassesint(isinstance(True, int)isTrue), so_to_idand_to_utcexplicitly rejectboolbefore checkingint. - Timestamp variations and unit mistakes: Strings ending in
"Z", lowercase"z", or explicit offsets like"+02:00"all convert to UTC ("16:20:00+02:00"becomes"14:20:00+00:00"). Naive strings lacking an offset ("2024-09-15T14:20:00") are rejected as ambiguous, and millisecond timestamps (1726410000000) passed where seconds were expected overflow year9999and raiseNormalizationError. - Blank strings and empty email entries: Whitespace-only strings (
" ") normalize toNone, and email entries in"api_b"missing a non-blank"value"are skipped cleanly. - Primary email fallback: When an email entry has
primary=True(even in second position as in Example 2),user.primary_emailreturns it; if none is flaggedprimary=True, it falls back touser.emails[0].address; ifuser.emailsis empty, it returnsNone. - Cross-source ID collisions: User
19in"api_a"and user"19"in"api_b"produce distinctuser.keyvalues ("api_a:19"vs"api_b:19").
Common mistakes
- Designing
Useraround one provider's JSON shape: Naming fieldsuserIdor keepingnamenested as a raw dict leaks one upstream schema into every caller. Model the domain entity, not the wire payload. - Typing
source_idasintor omittingsource: Typing IDs asintfails on prefixed strings like"usr_77b4", and omittingsourcelets"19"from two providers overwrite one another. - Using
bool(value)to parse status strings: In Python,bool("false")andbool("inactive")both evaluate toTruebecause any non-empty string is truthy! Always map string statuses through an explicit dictionary. - Storing naive
datetimeobjects or raw strings: Naivedatetimeobjects (tzinfo=None) raiseTypeErrorwhen compared against timezone-awaredatetimeobjects and lose timezone context. - Silently coercing unknown enum tokens or corrupt dates: Defaulting
"status": "suspended"toFalseor an unparseable timestamp todatetime.now()hides upstream breaking changes and corrupts stored records. - Using
= []as a dataclass default: Python raisesValueError: mutable default <class 'list'> is not allowedbecause all instances would share one list; always usefield(default_factory=list).
Alternative approaches
- Schema validation libraries (
Pydanticorattrs+cattrs): In production Python services, Pydantic v2 models provide declarative validation, structured field paths on errors, and fast JSON parsing. Even with Pydantic, keep one input schema or adapter per upstream API rather than piling conflicting alias rules onto the core domain class, and use strict boolean/integer validation so"true"orTrue-as-intis rejected. - Declarative field-mapping specs: When integrating dozens of similar providers, simple field-path mappings can live in config (
{"first_name": "name.given"}), while keeping custom Python functions for conditional rules like email-list filtering. - Adapter classes per integration: Wrapping
from_api_ainside anApiAAdapterclass implementing aUserAdapterprotocol becomes cleanly extensible once each integration also manages OAuth refresh tokens, rate-limit headers, and pagination cursors.
Follow-up questions
-
When persisting normalized
Userrecords in SQL, how should you split data between typed relational columns, child tables, and JSON columns, and what constraints or indexes belong on them? Use a hybrid relational + JSON layout: store shared normalized attributes (source,source_id,first_name,last_name,is_active,phone,time_zone,created_at) as typed SQL columns for fast filtering, sorting, and joins, and placeextras(alongsideraw_payloadfor replayability if a mapper bug is fixed later) in a PostgreSQLJSONBcolumn (binary-indexed JSON storage). Giveusersan internal UUID or auto-increment surrogate key (id, a database-generated primary key independent of upstream providers) plusUNIQUE (source, source_id)for conflict-free upserts, and normalizeemailsinto auser_emails (user_id, address, kind, is_primary)child table indexed onlower(address)so multi-email lookups stay fast without array scans. -
Suppose two upstream providers describe the same person with disagreeing attributes—how would you link those records without losing provenance, and how do you decide which field values win? Preserve every upstream record verbatim in
source_usersand link matching rows to acanonical_personstable through a mapping table so bad merges can always be audited and reversed without destroying raw provider state. Match deterministically first on verified normalized identifiers—such as lowercased email addresses or phone numbers formatted in E.164 (the international+14155550192standard)—and route fuzzy name + organization matches to human review rather than auto-merging. Resolve conflicting scalar values via explicit survivorship rules (field-level source priorities): trust the authoritative system of record per attribute (for example, HRIS beats a support tool on active status), break ties with the newer upstreamupdated_attimestamp, and take the union for multi-valued collections likeemails. -
If an upstream provider silently renames a property or alters its data type, how will your ingestion pipeline detect the drift while isolating healthy records and providers? Type changes (such as
isActivechanging fromfalseto"no") or missing required fields immediately raiseNormalizationErrorat the mapper boundary, routing only the offending payload into a quarantine (dead-letter) table (a holding table for unparseable payloads) and paging on the error-rate spike while existingUserrows and other providers continue running normally. Because renaming an optional field (sayphone->mobilePhone) silently leavesphone = Noneand shiftsmobilePhoneintoextras, track two per-provider observability signals: sudden jumps in columnNULLrates and novel key names appearing inextrasor nestedraw_payloaddicts. Once the mapper is patched, replaying quarantined or stored raw payloads backfills the renamed column cleanly. -
How would you design recurring sync jobs against each upstream API so polling stays incremental and retrying failed batches never duplicates or regresses stored data? Make database writes idempotent (yielding the exact same state whether applied once or repeatedly) via an upsert (
INSERT INTO users ... ON CONFLICT (source, source_id) DO UPDATE), guarded byWHERE EXCLUDED.source_updated_at >= users.source_updated_atwhen upstream modification timestamps exist so delayed retries never overwrite fresher data with older snapshots. Keep polling incremental by persisting a per-source watermark or sync cursor (the highest committedupdated_attimestamp or pagination token) and queryingupdated_since = watermark - 5 minutes; the short lookback window avoids boundary clock-skew gaps while idempotent upserts make re-processing those 5 minutes safe. Propagate upstream deletions via webhook/tombstone events or a periodic reconciliation sweep that marks unseen(source, source_id)records inactive.
Follow-up questions
- When persisting normalized `User` records in SQL, how should you split data between typed relational columns, child tables, and JSON columns, and what constraints or indexes belong on them?
- Suppose two upstream providers describe the same person with disagreeing attributes—how would you link those records without losing provenance, and how do you decide which field values win?
- If an upstream provider silently renames a property or alters its data type, how will your ingestion pipeline detect the drift while isolating healthy records and providers?
- How would you design recurring sync jobs against each upstream API so polling stays incremental and retrying failed batches never duplicates or regresses stored data?
Similar questions
- Company Hierarchy Operations: Organization Count, Depth Traversal, and Shared Supervisor
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager