Try Embedded

HTTP, REST and CoAP for IoT

REST design, HTTP versions, JSON versus CBOR, and CoAP.

When devices speak the web's language

HTTP is the most widely understood protocol on the internet. Firewalls allow it, every cloud service offers an HTTP API, and every developer can test it with a browser or curl. Devices use it to call cloud APIs, upload logs and images, download firmware, and to serve a local configuration page. Its cost on constrained devices is verbosity and per-request overhead, which is where CoAP comes in.

REST in one table

REST models a system as resources identified by URLs and manipulated with a small set of methods:

MethodMeaningIdempotentExample
GETRead a resourceYesGET /devices/42/config
POSTCreate, or perform an actionNoPOST /devices/42/readings
PUTReplace a resourceYesPUT /devices/42/config
PATCHPartially updateNot necessarilyPATCH /devices/42/config
DELETERemoveYesDELETE /devices/42/jobs/7

Status codes report the outcome: 2xx success (200 OK, 201 Created, 204 No Content), 3xx redirect, 4xx client error (400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, 429 too many requests), 5xx server error (retry later).

Idempotent matters for devices on flaky links: a request that timed out can be retried safely if it is idempotent. For POST, include a client-generated ID so the server can discard duplicates.

A request on the wire

POST /v1/devices/42/readings HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOi...
Content-Type: application/json
Content-Length: 41

{"t":1730000000,"temp":21.5,"rh":48.2}

Headers alone are often larger than the payload; for a device sending 40 bytes every minute over cellular, HTTP plus TLS overhead can be ten times the data.

HTTP versions

VersionKey traitsDevice relevance
HTTP/1.1Text, one request at a time per connection; keep-alive reuses connectionsSimplest; supported by every embedded client
HTTP/2Binary framing, multiplexed streams on one connection, header compression (HPACK)Less overhead for many requests; heavier library
HTTP/3Over QUIC (UDP), faster connection set-up, survives IP changesRare on MCUs so far

Reuse connections (keep-alive): a new TCP plus TLS handshake per request costs several round trips and significant energy.

Payload formats: JSON versus CBOR

JSONCBOR (RFC 8949)
EncodingTextBinary, same data model as JSON
SizeLarger: field names and numbers as textTypically 30 to 50% smaller
Parsing costText scanning, number conversionSimple, fast, little RAM
Human-readableYesNeeds a tool
Libraries on MCUscJSON, jsmn, JSON for Modern C++TinyCBOR, QCBOR, zcbor
#include <stdio.h>
#include <string.h>
#include <stdint.h>

int main(void) {
  /* The same reading, {"temp": 215, "rh": 482}, in JSON and in CBOR. */
  const char *json = "{\"temp\":215,\"rh\":482}";
  const uint8_t cbor[] = {
    0xA2,                               /* map with 2 pairs */
    0x64, 't', 'e', 'm', 'p',           /* text string, length 4 */
    0x18, 0xD7,                         /* unsigned int 215 (one extra byte) */
    0x62, 'r', 'h',                     /* text string, length 2 */
    0x19, 0x01, 0xE2                    /* unsigned int 482 (two extra bytes) */
  };
  printf("JSON: %u bytes\n", (unsigned)strlen(json));
  printf("CBOR: %u bytes\n", (unsigned)sizeof cbor);
  return 0;
}

Replacing field names with small integer keys shrinks CBOR further. Protocol Buffers are another compact choice when both ends share a schema.

CoAP: HTTP's ideas for constrained networks

CoAP (Constrained Application Protocol, RFC 7252) keeps REST (methods, URIs, response codes, content types) but redesigns the transport for tiny devices and lossy networks:

HTTPCoAP
TransportTCPUDP (also TCP and WebSockets variants)
HeaderText, hundreds of bytesBinary, 4-byte fixed header
ReliabilityFrom TCPOptional: confirmable messages are acknowledged and retransmitted; non-confirmable are not
SecurityTLSDTLS (CoAPS) or OSCORE (object security)
Server pushPolling or long-pollingObserve: subscribe to a resource and get notified on changes
Discovery—/.well-known/core lists a device's resources
Large payloadsStreamingBlock-wise transfer

CoAP fits NB-IoT, Thread and 6LoWPAN devices. LwM2M, a device-management standard built on CoAP, defines standard objects for firmware update, connectivity monitoring and sensors.

Authenticating devices

  • Mutual TLS: the device's certificate identifies it; no secret in the request. The strongest and most common for cloud IoT.
  • Bearer tokens (Authorization: Bearer ...): short-lived tokens such as JWTs, signed by the device's private key (Google Cloud IoT style) or issued by an auth service. Need a clock and refresh logic.
  • API keys: a static secret in a header. Simple, but leaks are common and rotation is painful; avoid for fleets.

Never put credentials in URLs (they end up in logs).

A local web server

Many devices serve a configuration page (Wi-Fi set-up, diagnostics). Keep it small: serve static files from flash (gzipped), expose a small JSON REST API for settings, require authentication, rate-limit login attempts, and do not leave a default password.

Pitfall: Many embedded HTTP clients do not follow redirects or handle chunked transfer encoding by default. A server change that adds a redirect or switches to chunked responses can break a fleet. Test against the real server and handle both.

Interview question: When would you choose CoAP over HTTP for a device?

Answer: When the device is very constrained or the network is lossy or low-bandwidth: NB-IoT, LoRa backhaul, Thread or 6LoWPAN meshes, battery devices where every byte transmitted costs energy. CoAP's compact binary header over UDP avoids TCP's handshake and connection state, confirmable messages give reliability when needed, Observe replaces polling, and DTLS or OSCORE provide security. HTTP is preferable when the device has ample resources and must talk to existing web APIs or through restrictive firewalls.

Interview question: JSON or CBOR for device payloads?

Answer: JSON when payloads are small or infrequent, the device has resources to spare, and human readability and ecosystem support matter, such as talking directly to web APIs. CBOR when bandwidth, energy or parsing cost matter: it uses the same data model, encodes 30 to 50% smaller, is faster to parse with less RAM, and is the natural pairing with CoAP and LwM2M. Using integer keys and a shared schema shrinks it further; Protocol Buffers are an alternative when both ends share a schema.

Build it: post readings without hammering the API

This is step 5, the last of the module project. Some buildings block MQTT, so the office air-quality monitor can also POST its readings to the cloud's HTTP API. Ten thousand monitors share that API. When it is overloaded and answers 503, a monitor that retries at once, or every 5 seconds forever, makes the outage worse; one that gives up loses data; and one that retries a request the server rejected as malformed retries forever. Each response needs the right reaction.

Lab: Read the response, then retry, back off or give up

  • http_parse(resp, r) reads a response held as text. The status line must be HTTP/1. and one digit, a space, and a 3-digit code: store the code in r->status, or return -1 if the line is not like that. Then read the header lines, up to the empty line that ends them: if one is named Retry-After (header names ignore case) and its value, after any spaces, is a whole number of seconds, store it in r->retry_after; otherwise leave it at -1. A Retry-After in the body does not count. Return 0.
  • http_next(r, attempt, delay) decides what to do with the response to try number attempt (0 for the first):
  • 200 to 299: ACT_DONE;
  • 401: ACT_REAUTH (get a new token, then send again);
  • 408, 429, 500 to 599, or status 0 (no usable response at all): ACT_RETRY, after retry_after seconds if the server gave one (at most 3600), otherwise after 5 << attempt seconds, at most 300;
  • any other code: ACT_DROP. The request itself is wrong, and sending it again will not help.

Set *delay to 0 for everything except ACT_RETRY.

Going deeper

Interview question: How would a smart energy meter send its readings to a cloud API reliably?

Answer: Buffer readings locally with timestamps, send them in batches over HTTPS (or CoAP on constrained links) with retries and exponential backoff, and only delete them once the server acknowledges. Make uploads idempotent (a reading ID) so a retry never double-counts, and keep enough storage to ride out a long outage.

Interview question: What is CoAP's Observe option?

Answer: A client registers interest in a resource with a GET carrying the Observe option, and the server then sends a notification each time the resource changes, instead of the client polling. It gives publish-subscribe-like behaviour within CoAP's request-response model, suitable for sensors that report on change. Notifications can be confirmable or not.

Interview question: Why would a device use HTTP/2 or keep-alive connections instead of new connections per request?

Answer: Each new HTTPS request on a fresh connection costs a TCP handshake and a full or resumed TLS handshake, several round trips and significant energy. Keeping one connection alive and reusing it for many requests (HTTP/1.1 keep-alive) or multiplexing several streams over it (HTTP/2, with compressed headers) removes that overhead after the first request.

Explain it: In your own words, explain why CBOR is often chosen over JSON on constrained devices.

Answer: CBOR encodes the same kinds of data as JSON, maps, arrays, numbers and strings, but in binary instead of text. Numbers take a few bytes instead of their decimal digits, structure markers are single bytes, and there is no need to escape or parse text, so messages are typically 30 to 50 percent smaller and much cheaper to encode and decode with little RAM. Smaller messages mean less radio time and energy, which matters on low-power links, and it pairs naturally with CoAP. JSON's advantage is that people can read it directly.