JAVASCRIPT

Standardizing External API Responses with Data Mapping

Learn to map and transform data from diverse external API structures into a consistent internal application format, improving data reliability and maintainability.

// Assume an external API returns data like this:
// { id: "a1b2c3d4", name: "Product X", price_cents: 1099, currency_code: "USD", stock_count: 50, created_at: "2023-10-26T10:00:00Z" }

// Desired internal format:
// { productId: "a1b2c3d4", productName: "Product X", price: 10.99, currency: "USD", availableStock: 50, createdAt: "2023-10-26T10:00:00Z" }

function transformProductApiResponse(rawData) {
  if (!rawData) {
    return null;
  }

  return {
    productId: rawData.id,
    productName: rawData.name,
    price: rawData.price_cents ? rawData.price_cents / 100 : 0, // Convert cents to dollars
    currency: rawData.currency_code,
    availableStock: rawData.stock_count,
    createdAt: rawData.created_at,
    // Add more transformations or default values as needed
  };
}

// Example usage:
// const apiResponse = {
//   id: "a1b2c3d4",
//   name: "Product X",
//   price_cents: 1099,
//   currency_code: "USD",
//   stock_count: 50,
//   created_at: "2023-10-26T10:00:00Z",
// };
// const standardizedProduct = transformProductApiResponse(apiResponse);
// console.log("Standardized product data:", standardizedProduct);

// You can also transform an array of items:
// const apiResponses = [ /* ...multiple product objects... */ ];
// const standardizedProducts = apiResponses.map(transformProductApiResponse);
How it works: This snippet illustrates how to transform and standardize data received from an external API into a consistent format used within your application. By mapping fields, renaming properties, and performing data type conversions (e.g., `price_cents` to `price`), you ensure that your application always works with predictable data structures, regardless of variations in the external API's response. This improves maintainability and reduces coupling.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs