Skip to content

Tutorial

Node-RED HTTP In Tutorial: Build an API and Receive ESP32 POST Data

Build a small REST API in Node-RED with http in and http response: POST/GET endpoints, validation and status codes, curl tests, an ESP32 sender and troubleshooting.

  • 10 min read
  • Updated November 14, 2026
Node-RED HTTP In Tutorial: Build an API and Receive ESP32 POST Data

Quick answer: to make an API in Node-RED, add an http in node (method POST, URL /api/sensor), wire it to a function node that checks msg.payload and sets msg.statusCode, and finish with an http response node. Every request must reach an http response node, or the client hangs until it times out. Node-RED parses a JSON body into msg.payload automatically when the client sends Content-Type: application/json. GET query strings arrive in msg.req.query, and path parameters such as /api/device/:id arrive in msg.req.params. An ESP32 then posts readings to http://<node-red-ip>:1880/api/sensor with HTTPClient.

Node / propertyWhat it does
http inCreates an endpoint (GET, POST, PUT, DELETE, PATCH) and starts a flow for each request
msg.payloadParsed request body (POST/PUT) or query object (GET)
msg.req.query / msg.req.params / msg.req.headersQuery string, :named path segments, request headers
http responseSends the reply; uses msg.payload, msg.statusCode and msg.headers
http requestThe opposite direction: Node-RED calling another API

HTTP or MQTT? Use HTTP when a device sends occasional data and wants a clear "accepted / rejected" answer, or when another service expects a webhook. Use MQTT for continuous telemetry and for sending commands to devices.

1. Create the endpoints

Build two small flows:

Flow A (receive data): http in (POST, /api/sensor) → function validate → http response Flow B (read the latest value): http in (GET, /api/sensor/latest) → function latest → http response

The URL is relative to Node-RED's HTTP root, so /api/sensor is served at http://<host>:1880/api/sensor. (If you set httpNodeRoot in settings.js, it becomes a prefix.) Avoid paths that start with Node-RED's own admin routes, such as /flows, /nodes or /settings.

Useful http in options:

OptionUse it for
MethodMatch the client: ESP32 data uploads are usually POST
URL with :name/api/device/:id → msg.req.params.id
Accept file uploads (POST)Multipart uploads such as camera images; files arrive in msg.req.files

Before writing any logic, wire http in → debug (complete msg object) and send a test request (section 3) to see exactly what arrives.

2. Validate the request and choose the status code

A request body from a device is untrusted input, even on your LAN. The function below checks a shared API key, validates the reading, stores the latest value in flow context for the GET endpoint, and always returns a status code. Set SOLDERHUB_API_KEY as an environment variable on the Node-RED host (or in the flow tab's Environment Variables), never inside the function code.

script.js
// POST /api/sensor  body: {"device":"esp32-01","temperature_c":24.6,"humidity_pct":51}
const expectedKey = env.get("SOLDERHUB_API_KEY");
const suppliedKey = msg.req.headers["x-api-key"];          // header names are lower-case

if (!expectedKey || suppliedKey !== expectedKey) {
  msg.statusCode = 401;
  msg.payload = { error: "unauthorized" };
  return msg;
}

const b = msg.payload;
const num = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
if (!b || typeof b !== "object" || !num(b.temperature_c, -40, 125) || !num(b.humidity_pct, 0, 100)) {
  msg.statusCode = 400;
  msg.payload = { error: "invalid_payload", expected: "temperature_c (-40..125), humidity_pct (0..100)" };
  return msg;
}

const reading = {
  device: String(b.device || "unknown").slice(0, 32),
  temperature_c: b.temperature_c,
  humidity_pct: b.humidity_pct,
  received: new Date().toISOString()
};
flow.set("latest", reading);                                 // for GET /api/sensor/latest

msg.statusCode = 201;                                        // 201 Created
msg.payload = { accepted: true, received: reading.received };
return msg;

For the GET endpoint, the latest function is three lines:

script.js
const latest = flow.get("latest");
msg.statusCode = latest ? 200 : 404;
msg.payload = latest || { error: "no_data_yet" };
return msg;
StatusWhen this API returns it
200 OKGET succeeded
201 CreatedReading accepted
400 Bad RequestMissing field, wrong type, out-of-range value, or malformed JSON
401 UnauthorizedMissing or wrong X-API-Key
404 Not FoundNo reading stored yet (or wrong URL)
500Something failed downstream (add a Catch node that returns this)

When msg.payload is an object, the http response node sends it as JSON with the right content type. To add headers, set msg.headers = { "Cache-Control": "no-store" } or use the node's Headers section.

Malformed JSON never reaches your function: Node-RED's body parser rejects it with a 400 before the flow starts. That's fine for devices, but remember to test it.

3. Test the API with curl

From any computer on the same network (on Windows, use PowerShell's curl.exe, or run the commands in Git Bash or WSL):

terminal
# Valid reading → 201
curl -i -X POST http://192.168.1.50:1880/api/sensor \
  -H "Content-Type: application/json" -H "X-API-Key: test-key-123" \
  -d '{"device":"esp32-01","temperature_c":24.6,"humidity_pct":51}'

# Wrong key → 401
curl -i -X POST http://192.168.1.50:1880/api/sensor \
  -H "Content-Type: application/json" -H "X-API-Key: wrong" -d '{"temperature_c":24.6,"humidity_pct":51}'

# Out of range → 400
curl -i -X POST http://192.168.1.50:1880/api/sensor \
  -H "Content-Type: application/json" -H "X-API-Key: test-key-123" -d '{"temperature_c":999,"humidity_pct":51}'

# Latest reading → 200 with JSON
curl -i http://192.168.1.50:1880/api/sensor/latest

-i shows the status line and headers, so you can confirm each code. Postman, Insomnia or the VS Code REST Client work just as well.

GET with query parameters

For simple devices that can only do GET, use /api/log?temp=24.6&hum=51: the values arrive as strings in msg.req.query (also copied to msg.payload), so convert them with Number() before validating. Query strings end up in server and proxy logs, so never put keys or passwords in them.

4. Send readings from an ESP32

This sketch connects to Wi-Fi and posts a JSON reading every 30 seconds with HTTPClient. Swap readTemperature() and readHumidity() for your real sensor (for example a DHT22 or BME280). Use the LAN IP of the Node-RED machine: 127.0.0.1 or localhost would point at the ESP32 itself.

sketch.ino
#include <WiFi.h>
#include <HTTPClient.h>

const char* WIFI_SSID = "REPLACE_WITH_WIFI";
const char* WIFI_PASS = "REPLACE_WITH_WIFI_PASSWORD";
const char* API_URL   = "http://192.168.1.50:1880/api/sensor";
const char* API_KEY   = "test-key-123";          // same value as SOLDERHUB_API_KEY
const unsigned long INTERVAL_MS = 30000;

unsigned long lastPost = 0;

float readTemperature() { return 24.6; }   // replace with your sensor
float readHumidity()    { return 51.0; }   // replace with your sensor

void postReading() {
  HTTPClient http;
  http.setTimeout(5000);                          // don't block forever if Node-RED is down
  http.begin(API_URL);
  http.addHeader("Content-Type", "application/json");
  http.addHeader("X-API-Key", API_KEY);

  char body[128];
  snprintf(body, sizeof(body),
    "{\"device\":\"esp32-01\",\"temperature_c\":%.1f,\"humidity_pct\":%.0f}",
    readTemperature(), readHumidity());

  int code = http.POST(body);
  if (code > 0) {
    Serial.printf("HTTP %d: %s\n", code, http.getString().c_str());
  } else {
    Serial.printf("POST failed: %s\n", http.errorToString(code).c_str());
  }
  http.end();
}

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) { delay(300); Serial.print("."); }
  Serial.printf("\nIP: %s\n", WiFi.localIP().toString().c_str());
}

void loop() {
  if (WiFi.status() == WL_CONNECTED && millis() - lastPost >= INTERVAL_MS) {
    lastPost = millis();
    postReading();
  }
}

Expected Serial Monitor output: HTTP 201: {"accepted":true,"received":"2026-…"}. A negative code such as -1 (connection refused) means the ESP32 never reached Node-RED; see the troubleshooting table below.

Need HTTPS? Use WiFiClientSecure with your server's root CA (client.setCACert(...)) and http.begin(client, "https://..."). Avoid setInsecure() outside a lab, since it skips certificate checks. For HTTPS on the Node-RED side, see Secure Node-RED.

5. Use the data

Once readings are validated, branch the validate output (after the response) to wherever they're needed:

Respond first and do the slow work afterwards, unless the client needs to know whether storage succeeded. In that case, send the response only after the write, and return 500 from a Catch node if it fails.

Troubleshooting

SymptomLikely causeFix
Request hangs, then times outSome path doesn't reach an http response nodeMake sure every branch (including errors) ends in http response
Cannot POST /api/sensor (404)Method or URL mismatch, or flow not deployedCheck the http in method and path; deploy
ESP32 POST failed: connection refused (-1)Wrong IP/port, firewall, or Node-RED not runningOpen http://<ip>:1880 from a phone on the same Wi-Fi; allow port 1880 in the firewall
msg.payload is a string, not an objectClient didn't send Content-Type: application/jsonAdd the header on the client
400 before your function runsMalformed JSON bodyCheck quotes and commas; test with curl
Always 401Env var not set, or header name differsRestart Node-RED after setting SOLDERHUB_API_KEY; read msg.req.headers in lower case
Browser fetch() blocked by CORSPage served from another originSet httpNodeCors: { origin: "*", methods: "GET,POST" } in settings.js (narrow the origin for real use)
Endpoint asks for a passwordhttpNodeAuth is setSend basic auth from the client, or use a separate key check as shown
Query values fail validationQuery params are stringsConvert with Number() first

Security checklist

  • Keep the API on your LAN or behind a VPN; don't port-forward 1880 to the internet.
  • Require a key (header) or httpNodeAuth, and use HTTPS where traffic leaves a trusted network.
  • Validate method, headers, body shape, types and ranges; reject everything else.
  • Give sensor-upload keys no power over relays or other outputs.
  • Keep keys in environment variables, not in flows, screenshots or query strings.
  • Protect the editor too: see Secure Node-RED.

FAQ

What URL does a Node-RED http in node use? http://<node-red-host>:1880 plus the path you set, for example http://192.168.1.50:1880/api/sensor, unless httpNodeRoot adds a prefix.

How do I get POST data in Node-RED? It's in msg.payload. JSON bodies are parsed into an object automatically when the request has Content-Type: application/json; form posts become an object of fields.

How do I read query parameters? From msg.req.query, for example msg.req.query.temp for ?temp=24. Values are strings.

What's the difference between http in and http request? http in receives requests (Node-RED is the server). http request sends requests to another API (Node-RED is the client).

Can the ESP8266 do the same? Yes: use ESP8266HTTPClient.h with a WiFiClient (http.begin(client, url)); the rest of the sketch is the same.

Next steps

Official references: Node-RED Cookbook: HTTP endpoints and Securing Node-RED.

Design the endpoint as a small API contract

An HTTP In node becomes easier to maintain when the request and response format are decided before the flow is built. For a sensor endpoint, document the method, path, expected content type, required fields, units and response codes. For example, accept a JSON object with a device identifier, temperature in degrees Celsius, humidity in percent and an optional measurement timestamp. Reject a request with an unsupported content type or missing required values rather than storing a partial record that looks valid.

Use appropriate status codes consistently:

StatusMeaning in this example
200A request was accepted and a representation is returned
201A new record was created
400JSON or required fields are invalid
401 / 403Authentication is missing or the caller is not allowed
404The requested route or device resource does not exist
405The route does not support the HTTP method
500An unexpected server-side failure occurred

The exact choice between 200 and 201 depends on whether the endpoint creates a resource or simply accepts a reading. Do not return 200 for every outcome: clients need to know whether to retry, correct the payload or stop.

Prevent duplicate and stale readings

Wi-Fi retries can cause a device to send the same measurement more than once. If duplicate storage matters, include a device identifier and a unique measurement ID or sequence number, then make the storage operation idempotent. A timestamp alone may not be unique when two readings are generated within the same second. Also decide whether the timestamp is generated by the device or the server; device clocks can be wrong after a reboot unless time synchronization has completed.

For a local experiment, a simple shared-network endpoint may be sufficient. For a deployed system, add authentication, rate limiting and input-size limits, and use HTTPS when requests cross an untrusted network. Never expose a Node-RED flow that controls relays or other physical equipment without an authorization check. Keep credentials outside the flow export and test the failure path as carefully as the successful POST request.

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.