I just started learning ESP8266 and in my first project I am successfully able to send data to ThingSpeak.com using ESP8266 with following code:

uploadData() {
  String apiKey = "ESDS8678890SDDS";
  String myData = "45.5"; // example of data to send
  if (espClient.connect(server,80)) {
    String postStr = apiKey;
    postStr +="&field1=";
    postStr += String(myData);
    postStr += "\r\n\r\n";
    espClient.print("POST /update HTTP/1.1\n");
    espClient.print("Host: api.thingspeak.com\n");
    espClient.print("Connection: close\n");
    espClient.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
    espClient.print("Content-Type: application/x-www-form-urlencoded\n");
    espClient.print("Content-Length: ");
    Serial.print("My Data: ");

But I have no idea how to retrieve data from ThingSpeak using ESP8266.

// Using XXXXX here as my channel is private
GET https://api.thingspeak.com/channels/XXXXXX/fields/1.json?results=2 

I think I have to use the above GET string to get the fields data. But I don't know how to create the request string.

Help would be appreciated.


migrated from electronics.stackexchange.com Apr 20 '16 at 5:03

This question came from our site for electronics and electrical engineering professionals, students, and enthusiasts.


Connect to the server as usual with espClient.connect(). The following request should return a JSON object containing your channel description and the first 2 entries in your feed:

espClient.println("GET /channels/CHANNEL_ID/feeds.json?results=2 HTTP/1.1");
espClient.println("Host: api.thingspeak.com");
espClient.println("Connection: close");

If it's a private channel, then you must supply your Read API key like this:

espClient.println("GET /channels/CHANNEL_ID/feeds.json?api_key=<your API key>&results=2 HTTP/1.1");

Notice that I use println() and not print() in order to implicitly terminate each request line properly. You should end each line not with \n but with \r\n. You only need to type this yourself if you use print().

To read the returned JSON data:

while (espClient.available() == 0);  // wait till something comes in; you may want to add a timeout here

unsigned long lastRead = millis();  // keeps track of last time a byte was read
while (millis() - lastRead < 2000) {  // while 2 secs havent passed since a byte was read
  while (espClient.available()) {
    lastRead = millis();   // update last time something was read
client.stop();  // close socket

To parse the JSON string, you either get a library from GitHub or you parse the string yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.