Retrieving Data from APIs using Mustache Templates (optional)

Retrieving Data from APIs using Mustache Templates

Overview

  • This is an optional step where you filter the JSON response in the Particle cloud before sending the JSON resposne to the Photon 2
  • This saves processing and bandwidth because you are only sending the Photon 2 the exact JSON data you want, not the whole JSON response
  • This is a good practice, but not explicitly required in our class.

Part 3: Subscribe to JSON response from Weather Stack

Photon 2 firmware

void setup() {
  // Subscribe to the integration response event
  Particle.subscribe("hook-response/JSONWeatherStack",
                      jsonSubscriptionHandler, MY_DEVICES);
}

##

Screenshot 2024-07-01 at 10.11.13 PM

##

Screenshot 2024-07-01 at 10.15.08 PM

##

Screenshot 2024-07-01 at 10.16.55 PM

##

Screenshot 2024-07-01 at 10.19.36 PM

##

Screenshot 2024-07-01 at 10.22.14 PM

Part 4 : Create Mustache template

  • Often we might only want a few items from the JSON, but the webserver sends the entire message
  • This extra data can waste time, bandwidth, power, and the response size can create errors
  • Instead, we can have Particle webserver send us only the data we actually want by creating Mustache templates

Example: Entire Weather Stack JSON Response

image-20200405005641533

Example: What if we only want the temperature?

right:50%

Creating Mustache Webhook Response Templates

Particle Console Webhook

image-20231012134414124

Example: Mustache Format

right:50%

  • If we are only interested in the temperature value which is nested in the current object, we could create a template like the following
  {"temp":"}"}
  • Now instead of the server sending entire JSON response, it will only send the following
    {"temp":"61"}
    
  • For webhook response templates, make sure the template will always result in valid JSON (i.e. {"name":"value"})

Part 5: Creating the function handler to receive and parse the JSON

Resources

Credits

Updated: