0

$USD

$USD
TUTORIALS ESP32ESP8266

ESP8266 Arduino Tutorial: HTTP PUT request

DFRobot Mar 11 2019 706

The objective of this esp32 tutorial is to explain how to perform a HTTP PUT request using the ESP8266 and the Arduino core. The tests from this tutorial were performed on a DFRobot’s ESP8266 FireBeetle board.

ESP32 Arduino HTTP PUT request



Introduction

The objective of this tutorial is to explain how to perform a HTTP PUT request using the ESP8266 and the Arduino core. For a version of this tutorial for the ESP32, please check here.

The request will be sent to a test fake online API, which can be seen here. In particular, we are going to send the request to this endpoint.

It’s important to take in consideration that, since this is a test API, nothing will really happen on the backend after we send our request. So, we will always receive the same answer independently of the content of our request.

However, the answer will be coherent with the HTTP method that we are using. Typically, PUT requests are used to update an already existing resource. You can read here a very interesting comparison between the PUT and the POST methods in the context of a REST API.

In our case, if we look into the endpoint we are going to reach, it includes a resource (“posts”), and an identifier (“1”), meaning that we are simulating an update to a “post” entity with ID equal to “1”.

As illustrated in figure 1, the response from the API  simulates a successful update to the mentioned entity (tested with Postman).

Figure 1 – Testing PUT request sent to the API with Postman.
The tests from this tutorial were performed on a DFRobot’s ESP8266 FireBeetle board.

The code

We will start our code by the library includes we need. We will need the ESP8266WiFi.h, which will allow us to connect the ESP8266 to a WiFi network, and the ESP8266HTTPClient.h, which will expose to us the functionality needed to perform the HTTP PUT request.

#include "ESP8266HTTPClient.h"
#include "ESP8266WiFi.h"

In order to be able to establish the connection to the WiFi network, we will need its credentials, more precisely, the network name and password. We will store these values in two global variables.

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

Moving on to the setup function, we will start by initializing the serial interface, so we can later output the results of our program.

Serial.begin(115200)

After that, we will connect the ESP8266 to the WiFi network, using the previously declared credentials.

WiFi.begin(ssid, password); 
 
while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
}

The full setup function can be seen below.

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 write the remaining code in the Arduino loop function. For this example, we will send a HTTP PUT request periodically and print the result returned by the server.

To start, we will need an object of class HTTPClient. We will use some methods of this class to setup and perform the request.

HTTPClient http;

After this declaration, we need to call the begin method on our HTTPClient object, passing as input the URL to which we want to send the request. Note that this method call is only used to setup the request and we will need to call another method below in order to actually send the request.

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

After this, we will specify the format of the body of the request by setting the value of the content-type header.

In a real application scenario, this is important in order for the server to know how to interpret the content of the request. For our example, the testing API will accept any content in any format and will always answer as if the body is correctly formatted, so we are only setting this header for illustration purposes.

So, in order to set the header, we need to call the addHeader method on our HTTPClient object, passing as first parameter the name of the header and as second parameter the value of the header.

Since, as already mentioned, the content-type doesn’t matter for the fake API testing server, we will simply set the content-type header to “text/plain“.

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

Then, to do the actual request, we still need to call the PUT method on the HTTPClient object.

This method receives as input the body content of the request and, in case of success, returns as output the HTTP response code from the server.

Note that success means that the request was successfully sent to the server without any error on the ESP8266 side. Naturally, there can be errors on the server side that are returned back modeled in an adequate HTTP response code. Nonetheless, from the perspective of the of the PUT method, the request was sent with success if it reached the server.

In case of error on the ESP8266 side, the value returned by the PUT method is lesser than zero (you can check here the possible values, for debugging in case of error).

As body of our request, we will send a simple test string, since the server will always accept the content. We will store the result of the method call in a variable, so we can check the response code from the server.

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

After sending the request, we will check if it was successful. We do this by confirming that the value returned by the PUT method is greater than zero.

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

In case it is, we will print both the HTTP status code and the content of the response returned by the server.

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

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

To finish our code, we need to call the end method on the HTTPClient object, to free the resources.

http.end();

The final code can be seen below. It contains a small delay between each iteration of the loop and the handling of the case where an internal error occurs when trying to send the request to the server.

We have also added a check to confirm the ESP8266 is still connected to the WiFi network before trying to send the HTTP request.

#include "ESP8266HTTPClient.h"
#include "ESP8266WiFi.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 device. Once the procedure finishes, open the Arduino IDE serial monitor.

The ESP8266 should periodically print the result of the request (body and HTTP response code), as shown in figure 2.

Figure 2 – Output of the program.

https://techtutorialsx.com/2019/01/30/esp8266-arduino-http-put-request/