Skip to content

Instantly share code, notes, and snippets.

@sheilnaik
Created May 14, 2020 04:01
Show Gist options
  • Save sheilnaik/2c6faf8a71233acf5bc513f36558cf9d to your computer and use it in GitHub Desktop.
Save sheilnaik/2c6faf8a71233acf5bc513f36558cf9d to your computer and use it in GitHub Desktop.
Sample code for calling retrieving JSON data from a REST API endpoint with JSON with headers
/* Note: You'll need to install the ArduinoJson library first before this will work
See https://www.youtube.com/watch?v=GUTpaY1YaXo for a 30-sec video showing how
More examples here: https://arduinojson.org/v6/how-to/use-arduinojson-with-esp8266httpclient/
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
// WiFi credentials
const char* ssid = "WIFI_NETWORK_NAME";
const char* password = "WIFI_NETWORK_PASSWORD";
void setup()
{
// Connect to WiFi
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting...");
}
}
void loop()
{
if (WiFi.status() == WL_CONNECTED)
{
HTTPClient http;
// Login to Home Assistant
http.begin("URL_GOES_HERE");
http.addHeader("Authorization", "Bearer API_KEY_GOES_HERE");
http.addHeader("Content-Type", "application/json");
http.GET();
// Parse response
DynamicJsonDocument doc(2048);
deserializeJson(doc, http.getStream());
// Read values
Serial.println(doc["attributes"]["media_artist"].as<char*>());
Serial.println(doc["attributes"]["media_title"].as<char*>());
// Disconnect
http.end();
}
delay(60000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment