liveBook · Manning

Dynamic key-value map

As explained in API Design Patterns

A dynamic key-value map is a map whose keys are arbitrary and not known when an API schema is defined.

A dynamic key-value map stores arbitrary pairs whose keys and structure are not known when an API schema is defined. Use it for dynamic data, not merely to regroup fields that already have a known shape. section 5.7

Choose between a map and a custom data type deliberately:

  • Use a custom data type when related fields are known, typed, and worth organizing under one field. section 5.7
  • Use a map when the data is arbitrary, dynamic, and has no expected structure. section 5.7

Ingredient amounts

A GroceryItem can expose ingredientAmounts as Map<string, string>, allowing entries such as fat, sodium, carbohydrate, sugar, fiber, and protein without adding a fixed field for every ingredient. section 5.7

Listing 5.10 Example JSON representation of an ingredients map
{
  "id": "514a0119-bc3f-4e3f-9a64-8ad48600c5d8",
  "name": "Pringles",
  "calories": "150",
  "ingredientAmounts": {
    "fat": "9 g",
    "sodium": "150 mg",
    "carbohydrate": "15 g",
    "sugar": "1 g",
    "fiber": "1 g",
    "protein": "1 g"
  }
}

Inspect a JSON representation of an ingredients map and its arbitrary keys and values. section 5.7

How API Design Patterns covers it

How deep it goes
Defines maps, contrasts them with custom data types, and demonstrates a typed map field with JSON.
Examples
Uses ChatRoom configuration grouping and GroceryItem ingredient amounts to compare fixed fields with map entries.
What you can do after
Evaluate whether an API field needs a predefined schema or should accept arbitrary key-value data.
How it connects
Contrasts dynamic maps with custom data types and relates both to resources, interfaces, and sub-resources.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of API Design Patterns. The section links point to the parts of the book it draws on.