ESP32 WebServer Library – arg()

Home / References / ESP32 Library / WebServer Library

Description

The arg() method is used within the ESP32 WebServer library to retrieve the value of an argument passed in an HTTP request (either GET or POST). You can access these arguments either by specifying the argument’s name or by its numerical index (position) in the list of received arguments.

This is essential for processing data submitted through web forms or parameters included in the URL’s query string.


Syntax and Usage

The arg() method can be used in two ways:

By Argument Name:

String value = server.arg(String name);String value = server.arg(const char* name);

Retrieves the value of the argument whose name matches the provided name string. This is the most common and readable way to access specific, expected parameters.

By Argument Index:

String value = server.arg(int index);

Retrieves the value of the argument at the specified zero-based index. This is useful when you need to iterate through all received arguments without knowing their names beforehand, often used in conjunction with the server.args() method (which returns the total number of arguments).

In both cases, server is an instance of the WebServer class (e.g., WebServer server(80);).

For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.


Argument(s)

The arg() method takes one argument, depending on the syntax used:

  • name (Type: String or const char*): The name (key) of the request argument whose value you want to retrieve. Argument names are case-sensitive.
  • index (Type: int): The zero-based index of the request argument whose value you want to retrieve. The index ranges from 0 to server.args() - 1.

Return Value

The arg() method returns a String:

  • If an argument with the specified name or at the specified index is found, the method returns its corresponding value as a String.
  • If no argument matches the given name or if the index is out of bounds, the method returns an empty String (“”).

It’s often good practice to check if an argument exists using server.hasArg(name) before attempting to retrieve its value with server.arg(name) to handle cases where parameters might be missing.


Example Codes

Below are examples demonstrating how to use the arg() method in different scenarios within an ESP32 WebServer application.

Example 1: Retrieving Arguments by Name

This example sets up a web server that listens for requests on the path /data. If the request includes query parameters like /data?sensor=temperature&value=25.3, the server retrieves the values for ‘sensor’ and ‘value’ using server.arg("sensor") and server.arg("value") and sends them back to the client.

/*
 * Author: Avant Maker
 * Date: April 21, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use ESP32 WebServer Library's 
 * arg() method to retrieves the values for 'sensor' and 'value'
 * using server.arg("sensor") and server.arg("value") and sends
 * them back to the client.
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their innovative ideas to life.
 */
#include <WiFi.h>
#include <WebServer.h>

// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

WebServer server(80); // Create a WebServer object on port 80

// Handler function for the /data path
void handleData() {
  String sensorName = "";
  String sensorValue = "";
  String response = "Received data:\n";

  // Check if the 'sensor' argument exists
  if (server.hasArg("sensor")) {
    sensorName = server.arg("sensor"); // Get value by name
    response += "Sensor: " + sensorName + "\n";
  } else {
    response += "Sensor parameter missing.\n";
  }

  // Check if the 'value' argument exists
  if (server.hasArg("value")) {
    sensorValue = server.arg("value"); // Get value by name
    response += "Value: " + sensorValue + "\n";
  } else {
    response += "Value parameter missing.\n";
  }

  server.send(200, "text/plain", response); // Send response to client
}

void setup() {
  Serial.begin(115200);
  Serial.println();

  // Connect to Wi-Fi
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Define request handlers
  server.on("/data", HTTP_GET, handleData); // Handle GET requests to /data

  // Start the server
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient(); // Listen for incoming client connections
  delay(2); // Allow yields for background tasks
}

To test this, connect your ESP32 to WiFi, upload the code, and then navigate to `http://[ESP32_IP_ADDRESS]/data?sensor=humidity&value=65` in your web browser. The browser should display the sensor name and value received.

Example 2: Retrieving Arguments by Index

This example demonstrates iterating through all arguments received in a request to the path /params. It uses server.args() to get the count, then loops from 0 to count-1, retrieving each argument’s name with server.argName(i) and its value with server.arg(i).

/*
 * Author: Avant Maker
 * Date: April 15, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use ESP32 WebServer Library's 
 * arg() method to iterate through all arguments received in a
 * request to the path /params.
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their innovative ideas to life.
 */
#include <WiFi.h>
#include <WebServer.h>

// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

WebServer server(80); // Create a WebServer object on port 80

// Handler function for the /params path
void handleParams() {
  String response = "Listing all received arguments:\n";
  int numberOfArgs = server.args(); // Get the total number of arguments

  response += "Number of arguments received: " + String(numberOfArgs) + "\n\n";

  // Loop through all arguments by index
  for (int i = 0; i < numberOfArgs; i++) {
    String argName = server.argName(i); // Get argument name by index
    String argValue = server.arg(i);    // Get argument value by index
    response += "Arg " + String(i) + ": " + argName + " = " + argValue + "\n";
  }

  server.send(200, "text/plain", response); // Send response to client
}

void setup() {
  Serial.begin(115200);
  Serial.println();

  // Connect to Wi-Fi
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Define request handlers
  // Handles both GET and POST requests to /params
  server.on("/params", handleParams); 

  // Start the server
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient(); // Listen for incoming client connections
  delay(2); // Allow yields for background tasks
}

To test this, after uploading, navigate to a URL like

http://[ESP32_IP_ADDRESS]/params?name=ESP32&core=dual&temp=22.5

The browser will display a list of all arguments (name, core, temp) along with their values.

error: Content is protected !!