Retrieving Data from APIs
Retrieving Data from APIs
Overview
- APIs provide useful data we can use in our device (e.g. weather and location data)
- Each API will be configured slightly differently but the process to connect is generally similar
##

##

##

##

##

Steps to Connect Photon 2 and API
- Determine how to use the API
- Create an integration -> webhook on Particle console
- Use
Particle.publishto trigger webhook - Use
Particle.subscribeto “listen” for response from webhook - Optional: Mustache template that tells the Particle Cloud to which relevant data from the response should be to the Photon 2 (and the rest of the data will be ignored)
- Create function handler that is used by
Particle.subscribeto process JSON
Step 0: How to use the API
- Each API is different, but they will usually have documentation that describes how to connect
- Typically, this will include
- Endpoint (URL you communicate with)
- Parameters to include in your request (e.g. name of city you want weather data for)
- How to obtain an API key (if necessary)
Step 0: How to Use the API
Example: WeatherStack

Step 1: Create Webhook In Particle Console
Particle integration settings

Part 2: Publish Event to Trigger Webhook
Photon 2 firmware
void loop() {
String data = "90089"; //USC zip code
// Trigger the integration
Particle.publish("JSONWeatherStack", data, PRIVATE);
// Wait 60 seconds
delay(60000);
}
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);
}
Example: Entire Weather Stack JSON Response

Weather Stack JSON Response (partial)
{
"current": {
"observation_time": "04:30 AM",
"temperature": 61,
"weather_code": 122,
}
}

Part 4: 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