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);
}
##

##

##

##

##

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

Example: What if we only want the temperature?

Creating Mustache Webhook Response Templates
Particle Console Webhook

Example: Mustache Format

- If we are only interested in the
temperaturevalue which is nested in thecurrentobject, 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
- The last step is to create Photon 2 code to handle / parse the JSON response
- While it is possible to manually parse JSON in C++, it is considered unsafe due to potential for security vulnerabilities
- Instead, use a library
- Instruction and examples for parsing JSON with
ArduinoJson
Resources
Credits
- Photo by Inset Agency on Unsplash