REST Response Normalization
Problem
Deeply nested API responses containing duplicate data make updates complex and error-prone. Updating a user’s name requires finding and changing it in multiple nested locations across the data structure. Components display inconsistent data when some nested copies update but others don’t. Memory usage balloons as the same entities get duplicated throughout the response tree.
Solution
Transform nested API responses into flat, ID-indexed structures that are easier to query and update. This prevents duplication and simplifies state management.
Example
This example demonstrates transforming API responses with inconsistent naming into a normalized format with predictable field names for easier use throughout the application.
// Transform API response into consistent format
function normalizeUser(apiResponse) {
return {
// Map API's user_id to standard id field
id: apiResponse.user_id,
// Map full_name to simplified name field
name: apiResponse.full_name,
// Map email_address to email field
email: apiResponse.email_address
};
}
// Use normalization to create consistent data structure
const user = normalizeUser(await fetch('/api/user').then(r => r.json()));
Benefits
- Eliminates data duplication by storing each entity once.
- Makes updates simple and consistent across the application.
- Reduces memory usage by avoiding duplicated nested entities.
- Simplifies querying and accessing specific entities by ID.
Tradeoffs
- Requires transformation logic to convert between API and normalized formats.
- Adds complexity when rendering components that need nested data.
- Can be overkill for simple APIs with minimal nesting or duplication.
- Needs denormalization when sending data back to the server.