Quick Answer

A sub-resource is a resource, which means it can have properties, sub-properties, and be as complex as any resource. The critical difference is that sub-resources do not appear alone but rather as members of a parent property. This is similar to how sub-properties are displayed, but there can be more than one sub-resource belonging to a parent property. For this reason, sub-resources are contained within a JSON array.

Digging Deeper

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. Repeated data will often come from two sources: values from associated multivalue fields and rows from a database table.

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

{
   "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 uses sub-properties because it assumes the mailing and shipping parent properties are unique in the resource object, but they still require their own (albeit similar) composite properties. Now what if we need 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 seeing how the above resource object would look using sub-resources:

{
   "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.

  • No labels