ESP32 Arduino: HTTP PUT request

In this tutorial, we will check how to send a HTTP PUT request using the ESP32 and the Arduino core. The tests from this tutorial were done using a DFRobot’s ESP32 module integrated in a ESP32 development board.

Introduction

In this tutorial, we will check how to send a HTTP PUT request using the ESP32 and the Arduino core.

We will be sending our request to a fake online testing API, to this endpoint. Since this API is for testing, our request won’t have any effect on the back-end status, and the answer from the server will always be the same, independently of the content of our request.

Figure 1 illustrates the expected result of sending a PUT request to the mentioned endpoint, using Postman (a very useful tool for testing HTTP requests).

Sending PUT request to fake online testing API, using Postman

Figure 1 – Testing the API with Postman.

As can be seen, the API simulates a successful update to an already existing resource (note that the URL contains a number that identifies a resource). You can check here a very interesting explanation about when to use PUT and a comparison with POST.

The tests from this tutorial were done using a DFRobot’s ESP32 module integrated in a ESP32 development board.

If you prefer a video version of this tutorial, please check my YouTube channel below:

The code

We will start the code by including the necessary libraries. The first one will be the WiFi.h, which will allow us to connect the ESP32 to a WiFi network. The second one will be the HTTPClient.h, which will expose to us the functionality needed to perform the PUT request.

#include "WiFi.h"
#include "HTTPClient.h"

We will also need to store the credentials of the WiFi network, so we can later connect to it. We will make use of two global variables to store those credentials, namely the network name and the password.

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

Moving on to the setup function, we will first open a serial connection, to output the results of our program. Additionally, we will connect the ESP32 to the WiFi network, using the credentials we have declared before.

void setup() {

  Serial.begin(115200);

  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 perform the actual request on the Arduino main loop. So, the first thing we will do is declaring an object of class HTTPClient. This object will expose to us the methods we will need to perform the PUT request.

HTTPClient http;

Next, we need to call the begin method on our object, passing as input the complete URL of the server endpoint to which we want to send the request.

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

After this, we should specify the content-type of the body of our PUT request, so the server knows how to interpret it.

Naturally, since we are reaching a fake testing API, the actual content we will send doesn’t matter. Nonetheless, for a real application scenario, it’s important to specify the content-type correctly.

In our case, we are going to send a simple testing plain text message. Thus, the content-type should be “text/plain“.

To specify the content-type header, which contains the mentioned information, we need to call the addHeader method on our HTTPClient object.

As first input this method receives the name of the header (“content-type”) and as second input the value of the header (“text/plain”).

http.addHeader("Content-Type", "text/plain");

To send the actual request, we need to call the PUT method of the HTTPClient object, passing as input the body content to send to the server.

In case of success, the method will return as output a value greater than zero, which corresponds to the HTTP response code. We will store it for error checking.

Note that success means that the request was sent to the server and no error occurred in the ESP32 side. Any HTTP status code that represents a back-end error means that the request was successfully sent to the server, but then some problem happened processing it in the back-end.

int httpResponseCode = http.PUT("PUT sent from ESP32");

After this, we will check if the value returned by the method is indeed greater than zero, so we know everything worked.

if(httpResponseCode>0){
// print server response
}

To get the server response, we simply need to call the getString method on the HTTPClient object. This method takes no arguments and returns the response as a string.

We will print the response, together with the HTTP response code from the server.

String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);

To finalize, we will call the end method on the HTTPClient object, to free the resources. This method takes no arguments and returns void.

http.end();

The final source code can be seen below. We have added a small delay between each iteration of the loop, so we are not constantly polling the server when testing this code.

We have also added a pre-check to confirm we are still connected to the WiFi network, before trying to do the request. Additionally, we have included the handling of the situation where an internal error occurs when trying to send the request to the server, where we print the error code to help debugging.

#include "WiFi.h"
#include "HTTPClient.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.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){

   HTTPClient http;   

   http.begin("http://jsonplaceholder.typicode.com/posts/1");
   http.addHeader("Content-Type", "text/plain");            

   int httpResponseCode = http.PUT("PUT sent from ESP32");   

   if(httpResponseCode>0){

    String response = http.getString();   

    Serial.println(httpResponseCode);
    Serial.println(response);          

   }else{

    Serial.print("Error on sending PUT Request: ");
    Serial.println(httpResponseCode);

   }

   http.end();

 }else{
    Serial.println("Error in WiFi connection");
 }

  delay(10000);
}

Testing the code

To test the code, simply compile it and upload it to your ESP32 device, using the Arduino IDE. After finishing, open the Arduino IDE serial monitor and wait for the WiFi connection to be established.

After that, as shown in figure 2, you should start seeing the response to the requests being periodically sent to the server, together with the status code 200 (the HTTP code for OK).

Sending PUT request to fake online testing API with ESP32 and Arduino core

Figure 2 – Output of the program, with the HTTP status code and server response.

Related Posts

One Reply to “ESP32 Arduino: HTTP PUT request”

Leave a Reply