ESP32: HTTP GET Requests

Introduction

The objective of this post is to explain how to perform simple HTTP GET requests using the ESP32 and the Arduino environment. To do so, we will use the HTTPClient.h library.

Important: Please note that at the time of writing this post, this library had just been merged with the Github master code, as can be seen here. So, you will most likely need to update your version of the ESP32 Arduino support libraries. You can check here the instructions on how to do it.

Note that you may have to both open Git GUI and run the get.exe file as administrator, on Windows, for the changes to take effect. If everything works fine, under the examples menu of the Arduino IDE, you should have an entry for HTTPClient examples. You can also view the examples at Github.

Although before the HTTPClient library was made available we could perform HTTP requests, this was more complex since we would have to deal with all the HTTP protocol over socket connections, as can be seen in this example. Fortunately, this library will hide much of the complexity and only expose easy to use functions.

So, in our simple example, we will connect to a WiFi network and do some HTTP GET requests to a fake online rest API website. You can explore this website here.

The code bellow is based on one of the basic examples provided with the HTTPClient library, which I encourage you to try.

If you prefer, you can check the video tutorial at my YouTube Channel:

The tests shown below were performed on a ESP32-E FireBeetle board from DFRobot.

The code for the HTTP GET requests

First of all, we will need to include the libraries for both connecting to a WiFi network and to perform the HTTP requests. You can check in more detail how to connect to a WiFi network with the ESP32 in this previous post.

We will also need to store the credentials of the WiFi network, so we can connect to it on the setup function. To do so, we will declare two global variables, as can be seen bellow. Note that you should change the values by your network credentials.

#include <WiFi.h>
#include <HTTPClient.h>
 
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

Now, in the setup function, we will open a serial connection, for printing debugging messages, and connect to the WiFi network. Please check the mentioned previous post if you need a detailed explanation on the procedure. Please maintain the delay before the WiFi.begin call, to guarantee that everything done in the background by the libraries starts fine. At the time of writing, if we didn’t include the delay, the connection to the WiFi network would fail most of the times.

void setup() {
 
  Serial.begin(115200);
  delay(4000);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
 
  Serial.println("Connected to the WiFi network");
 
}

We will send the HTTP requests on the Arduino main loop. First of all, we declare an object of class HTTPClient. This class will make available a lot of methods that will help us work with the HTTP functionalities without needing to worry with the low level implementation details. You can check the header file for a list of those methods.

HTTPClient http;

After that, we will call the begin method on the previously declared object, passing as a string parameter the URL where we want to perform the HTTP request. As we said, we are going to send the request to a testing website. You can directly access the URL in a web browser to check the expected content to be returned.

http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL

Now, to send the request, we just call the GET method on the http object. This methods receives no arguments and returns the HTTP code of the request, which we will store on a variable for error handling. Note that codes lesser than 0 are error codes from the library (you can check the list here) and values greater than zero are standard HTTP return codes.

So, if the code is greater than zero, we will print both the HTTP code returned and the response to our request. We get the response by calling the getString method, which receives no arguments and returns a string with the response. Otherwise, we will print an error message.

if (httpCode > 0) { //Check for the returning code
 
        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
 
}else {
 
      Serial.println("Error on HTTP request");
 
}

Finally, we will need to call the end method, to ensure the resources are freed. It’s important that we don’t forget this call.

http.end(); //Free the resources

You can check the full source code bellow, which already includes a small delay between each request. Also, before each request, we are checking if we are still connected to the WiFi network.

#include <WiFi.h>
#include <HTTPClient.h>
 
const char* ssid = "yourNetworkName";
const char* password =  "yourPassword";
 
void setup() {
 
  Serial.begin(115200);
  delay(4000);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
 
  Serial.println("Connected to the WiFi network");
 
}
 
void loop() {
 
  if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
 
    HTTPClient http;
 
    http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL
    int httpCode = http.GET();                                        //Make the request
 
    if (httpCode > 0) { //Check for the returning code
 
        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
      }
 
    else {
      Serial.println("Error on HTTP request");
    }
 
    http.end(); //Free the resources
  }
 
  delay(10000);
 
}

Testing the code

To test the code, just upload it with the Arduino IDE and open the serial monitor. You should get an output similar to figure 1. Note that we are getting an HTTP 200 code, which corresponds to an OK code.

ESP32 HTTP GET request
Figure 1 – Output of the HTTP GET program for the ESP32.

Just to confirm the results, you can check at figure 2 the output returned when accessing the URL directly on a web browser. As can be seen, the answer is the same.

Fake online REST API answer from ESP32 GET request
Figure 2 – Accessing the URL directly on a web browser.

47 thoughts on “ESP32: HTTP GET Requests”

  1. Hi Antepher,
    great tutorial. I am trying to do the same with ethernet shield. One question. Was that web url a plain HTML file? What i am planning is pull to some data from database with a php script and give it as a response. Hope it is gonna work.

  2. Hello, is it possible to read just the email adress out of the string? Not the whole content
    Thank you

    1. Not just on jasonplaceholder, it would be nice if I could access other websites and get informations like stock exchange or other values out of the string

  3. Excellent tutorials!! I’m trying ti make a http request using GET method to a node js server to store data in a database but I’m lost. I’m using the ESP32. Would you please provide any idea on how to do it? Thanks in advance.

  4. Sure would ;like to find a resource for adding headers using addHeader(name,value); The examples do not have this, and the library doesn’t go into it. I have tried using addHeader(name.value) after begin(host) and get a 401 return no headers attached.

Leave a Reply

Discover more from techtutorialsx

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

Continue reading