Skip to content

Tutorial

ESP32 REST API Tutorial: JSON Endpoints, API Key, CORS and mDNS

Turn an ESP32 into a JSON REST API: GET and POST endpoints, proper status codes, API key, CORS, mDNS, a complete sketch, plus Python and Home Assistant clients.

  • 7 min read
  • Updated November 2, 2026
ESP32 REST API Tutorial: JSON Endpoints, API Key, CORS and mDNS

Quick answer: an ESP32 REST API needs only the built-in WebServer library and ArduinoJson. Register routes with server.on("/api/v1/sensor", HTTP_GET, handler), build the reply with a JsonDocument and send it with server.send(200, "application/json", body). For POST, read the JSON body from server.arg("plain"), validate it, and answer with 400, 401, 404 or 422 when something is wrong. Add an API key header check for control endpoints, CORS headers for browser pages, and MDNS.begin("esp32-api") so clients can call http://esp32-api.local/… instead of an IP. A complete sketch combining all of this is at the end of the steps.

A web page served by an ESP32 is nice for humans. A REST API served by an ESP32 is useful for everything else: a phone app, a Python script, Home Assistant, Node-RED, a dashboard on another computer, a shell script that switches a relay with one command. Instead of returning HTML, the ESP32 returns small, clean JSON, and any software that speaks HTTP can read your sensors or control your hardware.

The good news is that you do not need any special library. The standard WebServer library included with the ESP32 core, plus ArduinoJson, is enough to build a proper API with multiple endpoints, input validation, authentication and cross-origin support. This tutorial builds one step by step: a status endpoint, a sensor endpoint, an LED control endpoint, an API key check and CORS headers.

What a REST API Is (The Short Version)

REST is a convention for using HTTP sensibly. You organize your device into resources (things with names, such as /api/v1/sensor or /api/v1/led) and use the HTTP method to say what to do:

MethodMeaningExample on the ESP32
GETReadGET /api/v1/sensor returns the temperature
POSTCreate or trigger an actionPOST /api/v1/led with {"state":"on"} turns an LED on
PUTReplace or set a valuePUT /api/v1/config updates a setting
DELETERemoveDELETE /api/v1/log clears stored data

Responses use status codes (200 success, 400 bad input, 401 unauthorized, 404 not found) and JSON bodies. Including /v1/ in the path lets you change the API later without breaking existing clients.

If you want the other side of this, the ESP32 calling someone else's API, see HTTP GET and POST requests.

What You Need

  • An ESP32 board
  • An LED with a 220 Ω resistor on GPIO 23 (or use the onboard LED on GPIO 2)
  • Arduino IDE with the ESP32 core
  • ArduinoJson version 7 from the Library Manager
  • A connection to your WiFi (see the WiFi tutorial)
  • curl (built into Windows 10+, macOS and Linux) or the Postman app for testing

Wire the LED: GPIO 23 to the 220 Ω resistor to the LED's long leg, and the short leg to GND.

Step 1: A Minimal API With Two Endpoints

sketch.ino
#include <WiFi.h>
#include <WebServer.h>
#include <ArduinoJson.h>

const char* ssid     = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";

const int LED_PIN = 23;
bool ledState = false;

WebServer server(80);

void sendJson(int code, JsonDocument& doc) {
  String body;
  serializeJson(doc, body);
  server.send(code, "application/json", body);
}

void handleStatus() {
  JsonDocument doc;
  doc["device"]  = "esp32-api";
  doc["uptime_s"] = millis() / 1000;
  doc["free_heap"] = ESP.getFreeHeap();
  doc["rssi"]    = WiFi.RSSI();
  doc["ip"]      = WiFi.localIP().toString();
  sendJson(200, doc);
}

void handleSensor() {
  JsonDocument doc;
  doc["chip_temperature_c"] = temperatureRead();   // internal chip sensor, rough value
  doc["analog_raw"]         = analogRead(34);
  sendJson(200, doc);
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  Serial.print("API at http://");
  Serial.println(WiFi.localIP());

  server.on("/api/v1/status", HTTP_GET, handleStatus);
  server.on("/api/v1/sensor", HTTP_GET, handleSensor);
  server.begin();
}

void loop() {
  server.handleClient();
}

Upload it and note the IP in the Serial Monitor. From any computer on the same network:

terminal
curl http://192.168.1.184/api/v1/status

You get JSON back:

config.json
{"device":"esp32-api","uptime_s":42,"free_heap":214532,"rssi":-58,"ip":"192.168.1.184"}

temperatureRead() returns the ESP32's internal chip temperature, which runs warm and is not an accurate room temperature. It is used here as a quick demo value. In a real project, replace it with a reading from a sensor such as a BME280 or DS18B20.

Step 2: A POST Endpoint to Control the LED

Control endpoints need to read the request body, validate it and respond appropriately.

sketch.ino
void handleLedGet() {
  JsonDocument doc;
  doc["state"] = ledState ? "on" : "off";
  sendJson(200, doc);
}

void handleLedPost() {
  if (!server.hasArg("plain")) {
    JsonDocument err;
    err["error"] = "Missing body";
    sendJson(400, err);
    return;
  }

  JsonDocument doc;
  DeserializationError e = deserializeJson(doc, server.arg("plain"));
  if (e) {
    JsonDocument err;
    err["error"] = "Invalid JSON";
    sendJson(400, err);
    return;
  }

  const char* state = doc["state"];
  if (!state || (strcmp(state, "on") != 0 && strcmp(state, "off") != 0)) {
    JsonDocument err;
    err["error"] = "state must be on or off";
    sendJson(422, err);
    return;
  }

  ledState = (strcmp(state, "on") == 0);
  digitalWrite(LED_PIN, ledState ? HIGH : LOW);

  JsonDocument ok;
  ok["state"] = ledState ? "on" : "off";
  sendJson(200, ok);
}

Register both routes in setup() on the same path with different methods:

sketch.ino
server.on("/api/v1/led", HTTP_GET,  handleLedGet);
server.on("/api/v1/led", HTTP_POST, handleLedPost);

Test it:

terminal
curl -X POST http://192.168.1.184/api/v1/led \
  -H "Content-Type: application/json" \
  -d '{"state":"on"}'

curl http://192.168.1.184/api/v1/led

On Windows Command Prompt, put the whole command on one line and escape the inner quotes: -d "{\"state\":\"on\"}".

The raw JSON body arrives under the special argument name "plain". Always validate input: return 400 for malformed requests and 422 when the JSON is valid but the values are not.

Step 3: Handle Unknown Routes

Without a handler, a wrong URL returns a plain-text error. A good API returns JSON for errors too.

sketch.ino
void handleNotFound() {
  JsonDocument doc;
  doc["error"]  = "Not found";
  doc["path"]   = server.uri();
  sendJson(404, doc);
}

// in setup():
server.onNotFound(handleNotFound);

Step 4: Protect It With an API Key

Anyone on your network can reach the API you just built, including a guest on your WiFi or a compromised device. At minimum, require a secret key on every control endpoint.

sketch.ino
const char* API_KEY = "change-this-to-a-long-random-string";

bool authorized() {
  if (server.header("X-API-Key") == API_KEY) return true;
  JsonDocument err;
  err["error"] = "Unauthorized";
  sendJson(401, err);
  return false;
}

void handleLedPost() {
  if (!authorized()) return;
  // ... rest of the handler as before
}

The WebServer only keeps headers you ask for, so register the header in setup() before server.begin():

sketch.ino
const char* headerKeys[] = {"X-API-Key"};
server.collectHeaders(headerKeys, 1);

Call it with the key:

terminal
curl -X POST http://192.168.1.184/api/v1/led \
  -H "X-API-Key: change-this-to-a-long-random-string" \
  -H "Content-Type: application/json" \
  -d '{"state":"on"}'

Be realistic about what this protects. The built-in WebServer speaks plain HTTP, so the key travels unencrypted across your WiFi. That is fine on a trusted home network, but anyone who can sniff the traffic can read it. Do not expose this API to the internet by forwarding a port. For remote access, put the ESP32 behind a VPN or a reverse proxy that adds HTTPS. Keep read-only endpoints open if you like, and put authentication on anything that changes the world.

Step 5: CORS, So a Web Page Can Call Your API

If you build a dashboard page on another host (or open a local HTML file) that calls your ESP32 with JavaScript, browsers block the request unless the ESP32 sends CORS headers.

sketch.ino
void addCors() {
  server.sendHeader("Access-Control-Allow-Origin", "*");
  server.sendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  server.sendHeader("Access-Control-Allow-Headers", "Content-Type, X-API-Key");
}

void sendJson(int code, JsonDocument& doc) {
  String body;
  serializeJson(doc, body);
  addCors();
  server.send(code, "application/json", body);
}

void handleOptions() {
  addCors();
  server.send(204);
}

// in setup():
server.on("/api/v1/led", HTTP_OPTIONS, handleOptions);

Browsers send an OPTIONS "preflight" request before a POST with custom headers, which is why that handler exists. Using * allows any website to call the API, so on a real device restrict it to your own dashboard's origin.

A tiny page to test it:

index.html
<button onclick="toggle()">Toggle LED</button>
<script>
async function toggle() {
  const r = await fetch("http://192.168.1.184/api/v1/led", {
    method: "POST",
    headers: {"Content-Type": "application/json", "X-API-Key": "your-key"},
    body: JSON.stringify({state: "on"})
  });
  console.log(await r.json());
}
</script>

The Complete Sketch (All Steps Together)

Steps 1–5 combined into one file you can upload as-is: status, sensor and LED endpoints, JSON errors, API-key protection on the LED, CORS, and mDNS.

sketch.ino
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <ArduinoJson.h>

const char* ssid     = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";
const char* API_KEY  = "change-this-to-a-long-random-string";
const int   LED_PIN  = 23;

WebServer server(80);
bool ledState = false;

void addCors() {
  server.sendHeader("Access-Control-Allow-Origin", "*");          // restrict in real use
  server.sendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  server.sendHeader("Access-Control-Allow-Headers", "Content-Type, X-API-Key");
}

void sendJson(int code, JsonDocument& doc) {
  String body;
  serializeJson(doc, body);
  addCors();
  server.send(code, "application/json", body);
}

void sendError(int code, const char* msg) {
  JsonDocument d;
  d["error"] = msg;
  sendJson(code, d);
}

bool authorized() {
  if (server.header("X-API-Key") == API_KEY) return true;
  sendError(401, "Unauthorized");
  return false;
}

void handleStatus() {
  JsonDocument d;
  d["device"] = "esp32-api";
  d["uptime_s"] = millis() / 1000;
  d["free_heap"] = ESP.getFreeHeap();
  d["rssi"] = WiFi.RSSI();
  d["ip"] = WiFi.localIP().toString();
  sendJson(200, d);
}

void handleSensor() {
  JsonDocument d;
  d["chip_temperature_c"] = temperatureRead();   // demo value; use a real sensor in projects
  d["analog_raw"] = analogRead(34);
  sendJson(200, d);
}

void handleLedGet() {
  JsonDocument d;
  d["state"] = ledState ? "on" : "off";
  sendJson(200, d);
}

void handleLedPost() {
  if (!authorized()) return;
  if (!server.hasArg("plain")) { sendError(400, "Missing body"); return; }
  JsonDocument in;
  if (deserializeJson(in, server.arg("plain"))) { sendError(400, "Invalid JSON"); return; }
  const char* s = in["state"];
  if (!s || (strcmp(s, "on") && strcmp(s, "off"))) { sendError(422, "state must be on or off"); return; }
  ledState = !strcmp(s, "on");
  digitalWrite(LED_PIN, ledState ? HIGH : LOW);
  handleLedGet();                                // return the new state
}

void handleOptions() { addCors(); server.send(204); }

void handleNotFound() {
  JsonDocument d;
  d["error"] = "Not found";
  d["path"] = server.uri();
  sendJson(404, d);
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  Serial.printf("API at http://%s/api/v1/status\n", WiFi.localIP().toString().c_str());

  if (MDNS.begin("esp32-api")) {                 // http://esp32-api.local
    MDNS.addService("http", "tcp", 80);
  }

  const char* headerKeys[] = {"X-API-Key"};
  server.collectHeaders(headerKeys, 1);

  server.on("/api/v1/status", HTTP_GET, handleStatus);
  server.on("/api/v1/sensor", HTTP_GET, handleSensor);
  server.on("/api/v1/led", HTTP_GET, handleLedGet);
  server.on("/api/v1/led", HTTP_POST, handleLedPost);
  server.on("/api/v1/led", HTTP_OPTIONS, handleOptions);
  server.onNotFound(handleNotFound);
  server.begin();
}

void loop() {
  server.handleClient();
}

esp32-api.local works on Windows 10/11, macOS, iOS and most Linux systems. Some Android versions don't resolve .local names, so keep the IP address (or a static IP) as a fallback.

Calling the API from Python and Home Assistant

Python (pip install requests):

main.py
import requests
BASE = "http://esp32-api.local/api/v1"
print(requests.get(f"{BASE}/status", timeout=5).json())
r = requests.post(f"{BASE}/led", json={"state": "on"},
                  headers={"X-API-Key": "change-this-to-a-long-random-string"}, timeout=5)
print(r.status_code, r.json())

Home Assistant (configuration.yaml): a sensor that polls the API and a command that switches the LED:

config.yaml
sensor:
  - platform: rest
    name: ESP32 chip temperature
    resource: http://192.168.1.184/api/v1/sensor
    value_template: "{{ value_json.chip_temperature_c }}"
    unit_of_measurement: "°C"
    scan_interval: 30

rest_command:
  esp32_led_on:
    url: http://192.168.1.184/api/v1/led
    method: POST
    headers:
      X-API-Key: !secret esp32_api_key
    content_type: application/json
    payload: '{"state":"on"}'

Restart Home Assistant after editing, and keep the key in secrets.yaml.

Design Tips for a Good ESP32 API

  • Use nouns, not verbs. POST /api/v1/led is better than /api/v1/turnLedOn.
  • Return the new state after a change so the client doesn't need a second request.
  • Keep responses small. A few hundred bytes is ideal on a microcontroller.
  • Validate everything, especially numbers that drive hardware.
  • Don't block in handlers. A handler that waits several seconds stalls every other client. Set a flag and return immediately.
  • Version your paths with /v1/ so changes don't break your apps.

Example endpoint plan for a small greenhouse node:

MethodPathPurpose
GET/api/v1/statusUptime, memory, Wi-Fi signal
GET/api/v1/sensorTemperature, humidity, soil moisture
GET/api/v1/relayCurrent relay state
POST/api/v1/relaySwitch the pump relay
POST/api/v1/configChange the watering threshold

Common Problems

SymptomLikely causeFix
404 for a route you definedPath differs (trailing slash, case)/api/v1/led and /api/v1/led/ are different routes
POST body emptyNo -d in curl, or wrong Content-TypeSend Content-Type: application/json; read server.arg("plain")
X-API-Key always emptycollectHeaders() missing or called after begin()Call it before server.begin()
CORS error in the browser consoleNo CORS headers or OPTIONS handlerAdd addCors() and the HTTP_OPTIONS route
API stalls with two clientsSynchronous WebServer handles one request at a timeKeep handlers fast; for many clients use ESPAsyncWebServer
esp32-api.local not foundmDNS unsupported on that client (some Android), or guest networkUse the IP address; same network for both devices
Works on laptop, not phoneDevices on different networksCheck both are on the same Wi-Fi/subnet
Windows curl JSON errorsSingle quotes in Command PromptUse -d "{\"state\":\"on\"}", or PowerShell's curl.exe

Frequently Asked Questions

Do I need ESPAsyncWebServer for a REST API? No. The built-in WebServer works well for simple APIs with a few clients. An async server helps when many clients connect at once, or you need WebSockets or fast file serving.

Can I call this API from Home Assistant? Yes: the REST sensor and rest_command examples above do exactly that. For deeper integration, see Home Assistant without MQTT.

REST or MQTT, which is better? REST is request/response and great for apps and scripts. MQTT pushes updates as they happen and suits sensors and automation.

Can the ESP32 serve HTTPS? The built-in WebServer is HTTP only. For encryption, keep the API on your LAN and use a VPN or an HTTPS reverse proxy for remote access.

Is it safe to expose this to the internet? Not without HTTPS and proper authentication. Use a VPN or a secure reverse proxy instead of port forwarding.

Where do I go next? Make the data live with WebSockets, let users set Wi-Fi without re-flashing with WiFiManager, or build a Wi-Fi smart switch.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.