ESP32 Arduino HTTP server: Getting query parameters

The objective of this post is to explain how to obtain the query parameters from an HTTP request sent to a webserver running on the Arduino core, on the ESP32. The tests of this ESP32 tutorial were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.


Introduction

The objective of this post is to explain how to obtain the query parameters from an HTTP request sent to a webserver running on the Arduino core, on the ESP32.

For an introduction to the HTTP asynchronous webserver on the ESP32, please consult this previous post.

The tests of this ESP32 tutorial were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.


The Arduino code

We will start the Arduino code by the needed library includes, which will allow to set the HTTP server and to connect the ESP32 to a WiFi network. We will also declare two global variables to hold the credentials for the Wireless Network to which we are going to connect the ESP32.

To finalize the declaration of global variables, we will need an instance of class AsyncWebServer, which receives as input of the constructor the port where the server will be listening for incoming requests.

#include <WiFi.h>
#include <FS.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

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

AsyncWebServer server(80);

Moving on to the setup function, we will start by opening a serial connection, so we can later output the results of the program, more precisely, the query parameters we are going to receive on the request.

After that, we are going to connect the ESP32 to the WiFi network, using the previously declared credentials. Note that at the end, after the connection is established, we print the IP of the ESP32 on the network, which will later be needed to connect to it.

Serial.begin(115200);

WiFi.begin(ssid, password);

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

Serial.println(WiFi.localIP());

Now we will setup a route on our server by binding it to a handling function. Inside that handling function, we will access the query parameters sent by the client.

We will use the index route (“/”) and specify that we will only receive HTTP GET requests on our route. Note that we will declare the handling function as a lambda function.

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
// Handling function
});

Inside the handling function, we will first check how many parameters were received. We can obtain this value by calling the params method on the request object, to which we receive a pointer as input of the handling function.

This method receives no arguments and, as said, will return the number of parameters received in the request.

int paramsNr = request->params();
Serial.println(paramsNr);

To obtain the actual parameters, we can use the getParam method of the same request object. This method receives as input the index (from 0 to number of parameters minus 1) of the parameter we want to obtain and returns a pointer to an object of class AsyncWebParameter, which contains the information about the parameter.

Since we already know the number of parameters from the previous call, we can do a for loop to obtain all the parameters.

We can obtain the name and the value of each parameter by calling the name and value methods on the AsyncWebParameter object, respectively.

Remember that we have a pointer to the object and not the actual object, so we need to use the -> operator to access the methods.

for(int i=0;i<paramsNr;i++){

     AsyncWebParameter* p = request->getParam(i);

     Serial.print("Param name: ");
     Serial.println(p->name());

     Serial.print("Param value: ");
     Serial.println(p->value());

     Serial.println("------");
}

Still inside the handling function, we will return the response to the client with a call to the send method on the request object. We will return a simple “Message received” string and a HTTP OK status.

request->send(200, "text/plain", "message received");

To finalize the Arduino setup function, we call the begin method on the global server object, to get the server started. The final complete source code can be seen below.

#include <WiFi.h>
#include <FS.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
 
const char* ssid = "yourNetworkName";
const char* password =  "yourNetworkPass";
 
AsyncWebServer server(80);
 
void setup(){
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
 
  Serial.println(WiFi.localIP());
 
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){

    int paramsNr = request->params();
    Serial.println(paramsNr);

    for(int i=0;i<paramsNr;i++){
        
        AsyncWebParameter* p = request->getParam(i);
        Serial.print("Param name: ");
        Serial.println(p->name());
        Serial.print("Param value: ");
        Serial.println(p->value());
        Serial.println("------");
    }
    
    request->send(200, "text/plain", "message received");
  });
 
  server.begin();
}
 
void loop(){}


Testing the code

To test the code, compile it and upload it to your ESP32 using the Arduino IDE. Then open the serial monitor and after the connection to the WiFi network finishes, use the IP that gets printed to send a GET request to the server from a web browser of your choice.

Since we want to test the query parameters, we will add some to our request. To do so, simply type the following on your browser’s address bar, changing {yourEspIp} by the IP printed to the serial monitor.

http://{yourEspIp}/?param1=10&param2=hello

After sending the request, you should get an output similar to figure 1, which shows the string we defined being returned. The query parameters are highlighted in the image.

Arduino ESP32 HTTP server GET request from chrome with query params

Figure 1 – Sending a HTTP GET request to the ESP32 webserver with query parameters.

If you go back to the Arduino Serial monitor, you should have an output like figure 2, which shows the number of parameters, their names and their values getting printed to the console. Note that they match the ones sent from the web browser.

ESP32 Arduino HTTP server getting query parameters.png

Figure 2 – Obtaining the query parameters of the HTTP request.


Related Posts

 

Advertisements
This entry was posted in ESP32 and tagged , , , , , , , , . Bookmark the permalink.

14 Responses to ESP32 Arduino HTTP server: Getting query parameters

  1. Pingback: ESP32 Arduino HTTP server: Running multiple server instances | techtutorialsx

  2. punit patel says:

    How can i get query parameters in ESP-IDF?????
    any lib.???

    Liked by 1 person

    • antepher says:

      Hi!

      Sorry, I don’t usually use the IDF, so I’m not aware of any good library for setting a HTTP Server and parsing query parameters.

      My suggestion is that you ask around the ESP32 forums or at the IDF GitHub page.

      Best regards,
      Nuno Santos

      Like

  3. Pingback: ESP8266 Arduino: Asynchronous HTTP web server | techtutorialsx

  4. Pingback: ESP32 Arduino HTTP Server: Serving HTML and JavaScript | techtutorialsx

  5. Pingback: ESP32 Arduino HTTP server: external and internal redirects | techtutorialsx

  6. Pingback: ESP32 Arduino HTTP server: route not found handling | techtutorialsx

  7. Pingback: ESP32 Arduino async server: Controlling HTTP methods allowed | techtutorialsx

  8. Pingback: ESP32 Arduino web server: getting client IP | techtutorialsx

  9. RB says:

    Can you call params by name instead of index? It looked like you could in the code docs but i dont seem to have much luck getting that to work, versus stepping thru them..

    Liked by 1 person

  10. Pingback: ESP32 Arduino: Temperature, humidity and CO2 concentration web server | techtutorialsx

  11. Nuns says:

    How can I Send /html/?parameter=2 directly from the sketch, I’ve tried.

    If I send via browser its ok,
    http://myESP/html/?parameter=154.56

    server.on(“/html/?deslocamento=1200”, HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, “text/html”, “deslocamento=1200”);
    });

    Liked by 1 person

    • antepher says:

      Hi!

      I’m not sure if I understood what you are trying to do.

      ?parameter=2 is a query parameter that you include when making the request to the server.

      In your case, it makes sense to work via browser, since the browser is sending a request to the ESP32. Thus the browser is your client.

      Then the server response doesn’t go in the query parameters. What you are doing with the request->send(200, “text/html”, “deslocamento=1200”); is basically returning to the browser html text answer equal to “deslocamento = 1200”, which is why most likely your browser is simply printing that string.

      So basically the client that will be contacting the server needs to know how to look in the HTTP response and handle that response.

      Note that in your case the second argument of the send method shoudn’t be text/html, since you are not returning html.

      It should be something like text/plain, since you are simply returning plaint text as an answer.

      Since your response has a structure, you can to other return types, such as json, which is easier to parse by clients, since there are out of the box libraries for most programming languages to parse that content type.

      Hope this helps 🙂

      Best regards,
      Nuno Santos

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s