Ugenz Academy/IoT Tutorial

Http Api Json And Websocket

9 min read1,629 words

Reading progress

Keep learning

ESP32 HTTP, API, JSON and WebSocket

Now we move from a simple ESP32 webpage to modern communication between ESP32 and web applications.

This topic is extremely important for IoT because it connects:

ESP32 │ ├── HTTP ├── REST API ├── JSON └── WebSocket │ ▼ Web App / Mobile App / Cloud

1. HTTP

HTTP (HyperText Transfer Protocol) is a communication protocol used between clients and servers.

For ESP32:

Phone / Browser │ │ HTTP Request ▼ ESP32 │ │ HTTP Response ▼ Phone / Browser

Example:

GET /temperature

ESP32 might respond:

29.5

2. HTTP Request and Response

Think of HTTP like asking a question.

Phone: "ESP32, give me temperature." ESP32: "Temperature is 29.5°C."

Technically:

Client │ │ GET /temperature ▼ ESP32 │ │ 200 OK │ 29.5°C ▼ Client

3. HTTP Methods

The most important HTTP methods are:

MethodPurpose
GETRead data
POSTSend/create data
PUTUpdate data
PATCHPartially update
DELETEDelete data

For simple IoT systems, you'll commonly see:

GET POST

4. GET Example

Suppose ESP32 provides:

/temperature

The browser sends:

GET /temperature

ESP32 returns:

29.5

In your ESP32 code:

server.on("/temperature", []() { server.send( 200, "text/plain", "29.5" ); });

Now:

http://ESP32-IP/temperature

returns:

29.5

5. API

An API (Application Programming Interface) allows one software system to communicate with another.

Instead of creating a webpage only for humans:

ESP32 → HTML → Browser

we can provide structured endpoints:

ESP32 │ ├── /api/temperature ├── /api/humidity ├── /api/light └── /api/status

A web application can request those endpoints.


6. IoT API Architecture

ESP32 │ ┌──────┴──────┐ │ │ Sensors Devices │ │ └──────┬──────┘ │ API │ ▼ Web Application │ ▼ Dashboard

7. What is JSON?

JSON = JavaScript Object Notation

JSON is a popular format for exchanging structured data.

Instead of:

29.5, 62, 1, 0

we can send:

{ "temperature": 29.5, "humidity": 62, "light": true, "motion": false }

Now the receiving application knows exactly what each value means.


8. JSON Structure

A JSON object uses:

key : value

Example:

{ "name": "ESP32", "temperature": 28.7 }

Here:

name → ESP32 temperature → 28.7

9. ESP32 Sensor API

Imagine your ESP32 has:

DHT22 PIR LDR

You could create:

GET /api/status

Response:

{ "temperature": 29.4, "humidity": 61, "motion": true, "light": 450 }

This is much more useful than sending plain text.


10. JSON API Example

Conceptually:

server.on("/api/status", []() { String json = "{"; json += "\"temperature\":29.4,"; json += "\"humidity\":61,"; json += "\"motion\":true"; json += "}"; server.send( 200, "application/json", json ); });

The important part is:

application/json

This tells the client:

The response contains JSON data.


11. Why JSON is Useful

Suppose you build a React dashboard.

Instead of receiving:

29.4

you receive:

{ "temperature": 29.4, "humidity": 61 }

JavaScript can easily access:

data.temperature

and:

data.humidity

So:

ESP32 │ │ JSON ▼ React / Next.js │ ▼ Dashboard

This is very useful for your web-development + IoT projects.


12. API for Controlling Devices

APIs aren't only for reading sensors.

They can control hardware.

For example:

POST /api/light

with:

{ "state": "on" }

ESP32:

JSON ↓ Parse ↓ state = on ↓ GPIO HIGH ↓ Light ON

13. GET vs POST Example

Reading

GET /api/status

Response:

{ "light": true, "fan": false }

Controlling

POST /api/light

Data:

{ "state": true }

This separation makes the system cleaner.


14. Query Parameters

You can also send values in URLs.

Example:

/api/led?brightness=80

Conceptually:

Browser │ │ brightness=80 ▼ ESP32 │ ▼ PWM = 80

This is useful for:

  • LED brightness
  • Servo angle
  • Motor speed
  • Temperature thresholds

15. JavaScript Fetch

A browser can call the ESP32 API using JavaScript.

Example:

fetch("http://192.168.1.105/api/status") .then(response => response.json()) .then(data => { console.log(data.temperature); console.log(data.humidity); });

The flow is:

JavaScript │ │ HTTP GET ▼ ESP32 API │ │ JSON ▼ JavaScript

16. Automatic Dashboard Updates

You can periodically request data.

setInterval(() => { fetch("/api/status") .then(response => response.json()) .then(data => { console.log(data.temperature); }); }, 2000);

This requests new data every 2 seconds.

0 sec → Request 2 sec → Request 4 sec → Request 6 sec → Request 8 sec → Request

This is called polling.


17. Problem With Polling

Imagine:

100 devices │ ├── request every second ├── request every second ├── request every second └── ...

That can generate unnecessary traffic.

For real-time applications, WebSocket can be better.


18. What is WebSocket?

WebSocket provides a persistent connection between client and server.

Normal HTTP:

Request ↓ Response ↓ Connection ends

WebSocket:

Client │ │ Connect ▼ Server │ │ │ Persistent connection │ ├──────► Data ◄────── Data ├──────► Data ◄────── Data

Both sides can send data when needed.


19. HTTP vs WebSocket

FeatureHTTPWebSocket
Request/responseYesNot required
Persistent connectionUsually noYes
Real-timeLimitedExcellent
Sensor dashboardGoodExcellent
Simple APIExcellentNot necessary
Live controlGoodExcellent

20. Example: Live Temperature

HTTP polling

Browser │ │ Request ▼ ESP32 │ │ 29°C ▼ Browser Wait 2 sec Browser │ │ Request ▼ ESP32

WebSocket

Browser ═════════════ ESP32 connection │ │ 29°C ▼ Browser │ │ 29.3°C ▼ Browser

The ESP32 can push updates as values change.


21. Smart Home WebSocket Example

Imagine your dashboard:

╔══════════════════════════════╗ ║ SMART HOME ║ ╠══════════════════════════════╣ ║ Temperature: 29.5°C ║ ║ Humidity: 61% ║ ║ Motion: DETECTED ║ ║ ║ ║ 💡 Light: ON ║ ║ 🌀 Fan: OFF ║ ║ 🚪 Door: CLOSED ║ ╚══════════════════════════════╝

When motion changes:

PIR │ ▼ ESP32 │ │ WebSocket ▼ Browser │ ▼ Motion: DETECTED

The page can update immediately without refreshing.


22. WebSocket for Your ESP32 Car

This is another great application.

Phone │ WebSocket │ ▼ ESP32 Car │ ▼ L298N │ ▼ Motors

Commands:

FORWARD BACKWARD LEFT RIGHT STOP

Because WebSocket keeps a connection open, control can feel more responsive than repeatedly loading pages.


23. REST API Architecture

A professional IoT architecture might look like:

Web App │ HTTPS │ ▼ Backend API │ │ ┌─────┴─────┐ │ │ Database MQTT │ ▼ ESP32

Or for a local project:

Phone │ Wi-Fi │ ESP32 │ REST API │ Sensors / Devices

24. ESP32 + React

Since you work with React, imagine:

React Frontend │ │ fetch() ▼ ESP32 API │ ├── DHT22 ├── PIR ├── Relay └── Servo

React could display:

Temperature: 28.9°C Humidity: 63% Motion: YES

And send:

POST /api/fan

to control the fan.


25. ESP32 + Next.js

A larger architecture could be:

Next.js Web Dashboard │ Backend │ ┌───────┴────────┐ │ │ Firebase API │ ▼ ESP32

This is closer to a production IoT system.


26. API Security

Never assume that an API is secure just because it is an API.

Avoid publicly exposing something like:

/api/door/open

without authentication.

Otherwise:

Attacker │ ▼ /api/door/open │ ▼ ESP32 │ ▼ Door opens

For real systems, consider:

  • Authentication
  • Authorization
  • HTTPS/TLS where appropriate
  • Strong credentials/tokens
  • Input validation
  • Rate limiting
  • Network segmentation
  • Secure firmware

27. JSON Data for Your Smart Home

A useful status response could be:

{ "temperature": 28.7, "humidity": 63, "motion": true, "light": true, "fan": false, "door": "closed", "security": "armed" }

Your frontend can turn that into:

╔══════════════════════════════╗ ║ SMART HOME ║ ╠══════════════════════════════╣ ║ 🌡 28.7°C ║ ║ 💧 63% ║ ║ 👤 Motion: YES ║ ║ 💡 Light: ON ║ ║ 🌀 Fan: OFF ║ ║ 🚪 Door: CLOSED ║ ║ 🔒 Security: ARMED ║ ╚══════════════════════════════╝

28. HTTP + JSON + WebSocket Together

These technologies can work together.

ESP32 │ ┌────────────┼─────────────┐ │ │ │ HTTP API WebSocket │ │ │ ▼ ▼ ▼ Web Pages JSON Live Data

For example:

HTTP ↓ Load dashboard API + JSON ↓ Get sensor/device state WebSocket ↓ Receive real-time updates

29. When to Use What?

Use HTTP when:

Simple request → response

Example:

GET /temperature

Use REST API + JSON when:

ESP32 ↔ Web/Mobile Application

Example:

GET /api/status POST /api/light

Use WebSocket when:

Real-time continuous communication

Example:

Live sensor dashboard Live robot control Live notifications

🧠 Quick Summary

HTTP │ ├── GET ├── POST ├── PUT └── DELETE API │ └── Endpoints ├── /api/status ├── /api/light └── /api/fan JSON │ └── Structured data { "temperature": 29.5, "humidity": 62 } WebSocket │ └── Real-time communication

The big picture:

ESP32 │ ┌──────────┼──────────┐ │ │ │ HTTP JSON WebSocket │ │ │ └──────────┼──────────┘ │ ▼ Web / Mobile App

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy