ESP32 minimal JSON webserver example for PlatformIO (ESPAsyncWebserver)

This is my recommended starting point to get a webserver running on the ESP32 using PlatformIO:

#include <Arduino.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>

AsyncWebServer server(80);

void setup() { 
  Serial.begin(115200);
  // Connect Wifi, restart if not connecting
  // https://techoverflow.net/2021/01/21/how-to-fix-esp32-not-connecting-to-the-wifi-network/
  WiFi.begin("MyWifiSSID", "MyWifiPassword");
  uint32_t notConnectedCounter = 0;
  while (WiFi.status() != WL_CONNECTED) {
      delay(100);
      Serial.println("Wifi connecting...");
      notConnectedCounter++;
      if(notConnectedCounter > 50) { // Reset board if not connected after 5s
          Serial.println("Resetting due to Wifi not connecting...");
          ESP.restart();
      }
  }
  Serial.print("Wifi connected, IP address: ");
  Serial.println(WiFi.localIP());

  // Initialize webserver URLs
  server.on("/api/wifi-info", HTTP_GET, [](AsyncWebServerRequest *request) {
      AsyncResponseStream *response = request->beginResponseStream("application/json");
      DynamicJsonDocument json(1024);
      json["status"] = "ok";
      json["ssid"] = WiFi.SSID();
      json["ip"] = WiFi.localIP().toString();
      serializeJson(json, *response);
      request->send(response);
  });

  // Start webserver
  server.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
}

Remember to replace your Wifi credentials! WiFi.begin("MyWifiSSID", "MyWifiPassword");

To your platformio.ini add:

monitor_speed = 115200
lib_deps =
    ESP Async [email protected]
    [email protected]

My complete platformio.ini looks like this:

[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200
lib_deps =
    ESP Async [email protected]
    [email protected]

Use PlatformIO’s Upload and Monitor so you can see the IP address of the device in your Wifi network, for example:

Wifi connected, IP address: 192.168.178.90

then goto http://192.168.178.90/api/wifi-info (replace 192.168.178.90 by the IP address of the ESP32 that you can see on the command line!

You should now see JSON like:

{
     status: "ok",
     ssid: "MyWifiSSID",
     ip: "192.168.178.90"
}

Remember that you can use a browser plugin like JSON Viewer for Chrome in order to auto-format JSON documents!