Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Sub-resources are normally used for two reasons. First, when the type of data represented by the sub-resource is not merely a composite of the parent property. Second, and most importantly, when the data represented by the sub-resource is subject to being repeated. To illustrateRepeated data will often come from two sources: values from associated multivalue fields and rows from a database table.

To visualize sub-resources, let's reconsider revisit the final resource object used created in the What is a sub-property? article: 

Code Block
languagejs
{
   "mailing":{
      "address":"PO Box 1234",
      "city":"New Orleans",
      "county":"Orleans",
      "state":"LA",
      "zip":"70116"
   },
   "shipping":{
      "address":"6649 N Blue Gum St",
      "city":"New Orleans",
      "county":"Orleans",
      "state":"LA",
      "zip":"70116"
   }
}

This sample resource object used uses sub-properties because it was assumed that assumes the mailing and shipping parent properties were are unique but each one had in the resource object, but they still require their own (albeit similar) composite properties. Perhaps Now what if we need a resource object that allows for one to many addresses. Perhaps we need a resource object that allows users to define the type of addresses. to display any number of addresses? What if users are allowed to define the address types? Either or both of these situations are perfect candidates for using sub-resources. Let's start by redesign seeing how the above resource object with would look using sub-resources instead of sub-properties:

Code Block
languagejs
{
   "addresses":[
      {
         "type":"Mailing",
         "address":"PO Box 1234",
         "city":"New Orleans",
         "county":"Orleans",
         "state":"LA",
         "zip":"70116"
      },
      {
         "type":"Shipping",
         "address":"6649 N Blue Gum St",
         "city":"New Orleans",
         "county":"Orleans",
         "state":"LA",
         "zip":"70116"
      }
   ]
}

We see that the mailing and shipping parent properties have been replaced with a single addresses parent property. Furthermore, to properly identify each address sub-resource, a type property has been added and the values of Mailing and Shipping have been assigned to them.