You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

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. To illustrate, let's reconsider the final resource object used 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 but require their own (albeit similar) composite properties. Perhaps we need a resource object that allows for any number of addresses. Perhaps we need a resource object that allows users to define the type of addresses. 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