ESP8266: HTTP GET Requests

Introduction

The objective of this post is to explain how to perform HTTP GET Requests using the ESP8266. If you prefer a video explanation, you can check my YouTube channel below:

The tests from this tutorial were performed using a NodeMCU board, a very cheap and easy to use ESP8266 board.

The setup

First, we need do include some libraries. Naturally, we need the ESP8266WiFi library, which provides to us the methods to connect to a WiFi network.

Then, we need the ESP8266HTTPClient library, which provides the methods to send HTTP requests. The header file for the ESP8266HTTPClient library can be seen here.

#include <esp8266wifi.h>
#include <esp8266httpclient.h>

To be able to connect to the WiFi network, we will need its credentials. So, we will define two global variables containing the network name (SSID) and password. Note that you should replace the placeholders in the code snippet below by the credentials of your network.

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

On the setup function, we will connect to the WiFi Network. This is done with a call to the begin method on the WiFi extern variable and providing the previously defined network credentials. More details about how to connect to a WiFi network using the ESP8266 are explained in this previous post.

We will also start a Serial connection to print the results of our program.

The complete Arduino setup function code can be seen below.

void setup () {

  Serial.begin(115200);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }

}

The main code

The code for the request will be specified in the Arduino main loop function. First, we declare an object of class HTTPClient, which we will simply call http. This class provides the methods to create and send the HTTP request.

HTTPClient http;

After that, we will call the begin method on the http object and pass the URL that we want to connect to and make the HTTP GET request. The destination website specified here implements a dummy REST API for testing and prototyping.

Note that the particular endpoint we are reaching will return a JSON payload as response, simulating a possible “user” data structure. You can directly access the URL and check the result in a web browser. Later, when testing the ESP8266 code, we should receive the same response.

http.begin("http://jsonplaceholder.typicode.com/users/1");

Then, we send the request by calling the GET method on the http object. This method will return the status of the operation, which is important to store for error handling. If the value is greater than 0, then it is a standard HTTP code. If the value is lesser than 0, then it is a client error, related with the connection. All available error codes for this method are listed here.

int httpCode = http.GET();

So, if the code is greater than 0, we can get the response payload by calling the getString method on the http object. The response is returned as a String, which we can directly print to the serial port.

String payload = http.getString();
Serial.println(payload);

Finally, we will call the end method. This is very important to close the TCP connection and thus free the resources.

http.end();

The final complete code is shown bellow. Note that we have added a small delay of 30 seconds between each iteration of the Arduino main loop, to avoid constantly polling the server.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void setup () {

  Serial.begin(115200);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }

}

void loop() {

  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

    HTTPClient http;  //Declare an object of class HTTPClient

    http.begin("http://jsonplaceholder.typicode.com/users/1");  //Specify request destination
    int httpCode = http.GET();                                  //Send the request

    if (httpCode > 0) { //Check the returning code

      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);             //Print the response payload

    }

    http.end();   //Close connection

  }

  delay(30000);    //Send a request every 30 seconds
}

Testing the code

To test the code, simply compile it and upload it to your device using the Arduino IDE.

After the upload procedure finishes, open the IDE serial monitor and wait for the WiFi connection to be established. Once this procedure is done, the ESP8266 should start sending the HTTP GET requests to the server periodically.

The expected output of the program is shown in figure 1. The response printed to the serial monitor corresponds to the JSON payload returned by the server. The ESP8266 should keep doing a HTTP GET request every 30 seconds.

Output of the ESP8266 GET Request program, on the Arduino IDE serial monitor
Figure 1 – Output of the GET Request.

Finally, it’s important to take in consideration that the microcontroller has a limited amount of resources and thus it is not able to handle very large results. So, it is not expected that it will be used to make and process requests to sites that return a lot of information, as a typical browser would do.

Related Posts

Technical details

  • ESP8266 libraries: v2.3.0
  • Operating system: Windows 8.1

315 thoughts on “ESP8266: HTTP GET Requests”

    1. Hi! It doesn’t show anything after making the HTTP request or even at the beginning, when connecting to the WiFi network?

      If you don’t see a “Connecting..” message right after uploading the code, it’s probable that there is some problem with the hardware or the baud rate of the serial monitor is not matching the baud rate defined in the code. Is your serial monitor configured for 115200 baud?

      If it is after the request, it may have been some temporary problem with the destination website. Can you access the URL directly in your web browser?

      If you changed the example website provided in this tutorial to other website that returns a lot of content as response to the HTTP request, then the ESP may have not been capable of handling so much data.

        1. Hi,

          You are trying to do an HTTPS request, which means the connection is secured (the S stands for secure).

          The tutorial is applicable to HTTP requests, which is why it is not working for the URL you mentioned.

          I haven’t yet tried HTTPS on the ESP8266 but there was an example in the Arduino libraries:
          https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino

          https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/client-secure-examples.rst

          I remember that at the time the HTTPS support was very limited on the ESP8266 due to memory constraints. For example, it was not possible to validate the whole certificate chain, which is crucial when working with HTTPS.

          I don’t know if things have evolved since then on the ESP8266, but I can confirm however that HTTPS works well on the ESP32:
          https://techtutorialsx.com/2017/11/18/esp32-arduino-https-get-request/

          The ESP32 is more capable for handling the computation and memory requirements needed for secure connections, so if you are looking for something scalable which needs HTTPS I would recommend you to check the ESP32.

          Hope this helps,
          Nuno Santos

    2. Hello,
      I tried the code but the payload is empty, I tried using the browser and it shows the information as decribed in this webpage, what could be wrong ?

      1. Hi!

        Did you run the code multiple times? maybe it was a temporary unavailability on the website. Or is it occurring always?

        Are you able to send requests to other websites with the code from the tutorial?

    1. Hi! It doesn’t show anything after making the HTTP request or even at the beginning, when connecting to the WiFi network?
      If you don’t see a “Connecting..” message right after uploading the code, it’s probable that there is some problem with the hardware or the baud rate of the serial monitor is not matching the baud rate defined in the code. Is your serial monitor configured for 115200 baud?
      If it is after the request, it may have been some temporary problem with the destination website. Can you access the URL directly in your web browser?
      If you changed the example website provided in this tutorial to other website that returns a lot of content as response to the HTTP request, then the ESP may have not been capable of handling so much data.

        1. Hi,
          You are trying to do an HTTPS request, which means the connection is secured (the S stands for secure).
          The tutorial is applicable to HTTP requests, which is why it is not working for the URL you mentioned.
          I haven’t yet tried HTTPS on the ESP8266 but there was an example in the Arduino libraries:
          https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino
          https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/client-secure-examples.rst
          I remember that at the time the HTTPS support was very limited on the ESP8266 due to memory constraints. For example, it was not possible to validate the whole certificate chain, which is crucial when working with HTTPS.
          I don’t know if things have evolved since then on the ESP8266, but I can confirm however that HTTPS works well on the ESP32:
          https://techtutorialsx.com/2017/11/18/esp32-arduino-https-get-request/
          The ESP32 is more capable for handling the computation and memory requirements needed for secure connections, so if you are looking for something scalable which needs HTTPS I would recommend you to check the ESP32.
          Hope this helps,
          Nuno Santos

    2. Hello,
      I tried the code but the payload is empty, I tried using the browser and it shows the information as decribed in this webpage, what could be wrong ?

      1. Hi!
        Did you run the code multiple times? maybe it was a temporary unavailability on the website. Or is it occurring always?
        Are you able to send requests to other websites with the code from the tutorial?

  1. Pingback: techtutorialsx

  2. Pingback: techtutorialsx

  3. Pingback: ESP8266: Posting JSON data to a Flask server on the cloud | techtutorialsx

  4. Pingback: ESP8266: Posting JSON data to a Flask server on the cloud | techtutorialsx

    1. Hi! This already has the full code. Do you mean putting it all together from the beginning to the end in a section of the post, like I’ve been doing in more recent posts? If so, sure, I will update the post as soon as I can with a section listing all the code.

    1. Hi! This already has the full code. Do you mean putting it all together from the beginning to the end in a section of the post, like I’ve been doing in more recent posts? If so, sure, I will update the post as soon as I can with a section listing all the code.

Leave a Reply to mauricioCancel reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading