CoAP Methods and Multicast: Reference
More
Depth: Practitioner
Progress saves as you read. Mark sections complete as you go; your progress appears in the sidebar.
Related reference: CoAP message types.
This page preserves the original supporting material for CoAP Methods and Multicast. The five figure blocks remain in that chapter in their original order; the five multiple-choice checks are collected on the standalone check page. Original walkthroughs and runtime cells below are retained without revision.
Learning Objectives
- Choose GET, POST, PUT, or DELETE from the intended resource change and explain what a repeat may do.
- Diagnose the gap between a successful response and a verified device state in the Python and ESP32 examples.
- Use scoped multicast discovery to find candidate resources without assuming every server replied.
- Choose Observe for change reporting while checking freshness and notification overhead.
- Audit byte and energy assumptions before using a calculator result in a protocol decision.
For the tank panel, the address identifies the alarm-limit resource and PUT carries its desired value. The server answers with a response code, which the panel must inspect. If the response is missing, the panel needs a retry and verification rule.
The four-byte base header is only the start of a CoAP message. Tokens, options describing the resource, payload framing, and the payload add bytes. Network and security layers add more. A compact header helps a byte budget; it does not establish device battery life.
Now extend the tank example to several sensors. Multicast sends a request to a group address rather than one server. It reduces outgoing requests, while each responding sensor still contributes traffic. For the illustrative group of fifty, replacing fifty requests with one removes 49/50, or 98%, of outgoing requests; it does not remove 98% of the whole exchange.
Use a non-confirmable group GET for discovery, then collect individual unicast replies. Missing replies leave uncertainty about which devices are present. A group command also needs an authorization and outcome rule for each device.
Continue: CoAP Method Codes and Multicast Contracts
The main chapter below stays focused on the core methods and feature tour. For the deeper contract behind compact method and response codes, safe/idempotent retry behavior, multicast discovery, Location options, Token correlation, and Leisure response spreading, continue to CoAP Method Codes and Multicast Contracts.
CoAP Methods
Return to the lost tank reply. Repeating the same fixed-limit PUT preserves the intended setting; issuing another create-record POST may add another record. Idempotency names this distinction in intended effects, not identical response codes. Safe means the client is not requesting a state change: GET is safe, while PUT and DELETE can change state.
Distinguish a protocol retransmission from a new application request. Duplicate handling of a retransmitted message does not give every fresh POST an idempotency guarantee. Use this table after predicting the operation:
| Method | Purpose | HTTP Equivalent | Idempotent |
|---|---|---|---|
| GET | Retrieve resource | GET | Yes |
| POST | Process supplied data; may create a subordinate resource or trigger an action | POST | Not guaranteed |
| PUT | Update/Create | PUT | Yes |
| DELETE | Remove resource | DELETE | Yes |
Examples
Read the examples by the state transition each method promises. GET retrieves the current /temperature representation without changing it. POST sends a new reading to the /readings collection, allowing the server to create a subordinate resource. PUT replaces the known /config representation with the supplied interval, so an identical retry has the same intended state. DELETE removes /readings/old. URI, method, payload, and expected response code should be reviewed together before any of these exchanges is implemented.
GET: Retrieve temperature
coap://sensor.local/temperature
POST: Add new sensor reading
coap://server.local/readings
Payload: {"temp": 23.5, "time": "2025-10-24T23:30:00Z"}
PUT: Update configuration
coap://device.local/config
Payload: {"interval": 60}
DELETE: Remove old data
coap://server.local/readings/old
Checkpoint: Method Semantics
You now know:
- CoAP carries the same four REST verbs as HTTP: GET, POST, PUT, and DELETE.
- GET, PUT, and DELETE have idempotent semantics; POST has no general guarantee for a fresh repeat.
- Transfer the tank rule to the thermostat below: read temperature, set a fixed target, and invoke a reset. A reset action still needs a repeat policy.
Code Examples
Read the snippets as partial examples. They are preserved here for inspection, not presented as a tested end-to-end configuration lab. The Python server refers to resource without an explicit import, mounts only /temperature, and its PUT handler prints bytes without storing a setting. The client’s /config PUT therefore has no matching resource in that server. A Changed response from a handler that only prints does not prove the requested setting was saved.
Python CoAP Server
import asyncio
from aiocoap import *
class TemperatureResource(resource.Resource):
"""Example resource for temperature readings"""
async def render_get(self, request):
"""Handle GET requests"""
temperature = 22.5 # Simulated sensor reading
payload = f"{temperature}".encode('utf-8')
return Message(
code=Code.CONTENT,
payload=payload,
content_format=0 # text/plain
)
async def render_put(self, request):
"""Handle PUT requests to update config"""
print(f'Received: {request.payload}')
return Message(code=Code.CHANGED)
async def main():
# Create CoAP server
root = resource.Site()
# Add temperature resource
root.add_resource(
['temperature'],
TemperatureResource()
)
# Start server
await Context.create_server_context(root)
print("CoAP server started on port 5683")
await asyncio.get_running_loop().create_future()
if __name__ == "__main__":
asyncio.run(main())

Knowledge check · self-test
Knowledge check
Test your understanding.
Install: pip install aiocoap
Python CoAP Client
The executed GET targets the mounted /temperature resource. The separate update_config() function is defined but never called by the final line. To evaluate an update implementation, inspect both the response and a subsequent read of stored state; these snippets do not supply that storage contract.
import asyncio
from aiocoap import *
async def get_temperature():
"""Fetch temperature from CoAP server"""
# Create CoAP client protocol
protocol = await Context.create_client_context()
# Build GET request
request = Message(
code=Code.GET,
uri='coap://localhost/temperature'
)
try:
# Send request
response = await protocol.request(request).response
print(f'Response Code: {response.code}')
print(f'Temperature: {response.payload.decode("utf-8")}°C')
except Exception as e:
print(f'Failed to fetch: {e}')
async def update_config():
"""Send PUT request to update configuration"""
protocol = await Context.create_client_context()
request = Message(
code=Code.PUT,
uri='coap://localhost/config',
payload=b'{"interval": 30}'
)
response = await protocol.request(request).response
print(f'Update result: {response.code}')
# Run client
asyncio.run(get_temperature())
Arduino ESP32 CoAP Client
This client requests temperature and prints received payloads. It waits ten seconds before servicing coap.loop(), so it is not evidence of prompt response handling or complete retry behavior. Its Message ID printout alone cannot establish a matching successful response.
#include <WiFi.h>
#include <coap-simple.h>
// WiFi credentials
const char* ssid = "YourWiFi";
const char* password = "YourPassword";
// CoAP client
Coap coap;
// CoAP server details
IPAddress serverIP(192, 168, 1, 100);
int serverPort = 5683;
void callback_response(CoapPacket &packet, IPAddress ip, int port) {
char payload[packet.payloadlen + 1];
memcpy(payload, packet.payload, packet.payloadlen);
payload[packet.payloadlen] = NULL;
Serial.print("CoAP Response: ");
Serial.println(payload);
}
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
// Start CoAP
coap.response(callback_response);
coap.start();
}
void loop() {
// Send GET request every 10 seconds
int msgid = coap.get(serverIP, serverPort, "temperature");
Serial.print("Request sent, MID: ");
Serial.println(msgid);
delay(10000);
coap.loop();
}
Interactive Comparison: CoAP vs MQTT vs HTTP
The chart uses fixed illustrative values. Its battery years, latency and complexity scores have no measurement evidence here. Its header bars also compare different amounts of framing. Use the controls to inspect the assumptions; do not use the ranking as a benchmark or a battery forecast.
CoAP Advantages:
- A four-byte base header supports compact resource messages, before other fields and layers.
- GET and PUT make reads and desired-state settings explicit.
- UDP avoids TCP connection setup for this binding; security and application exchanges can still add setup work.
When CoAP Wins:
For the tank panel, directly addressable resources and short datagram exchanges are reasons to evaluate CoAP. Measure the complete exchange on the target device before accepting an energy or latency requirement.
When to Choose Alternatives:
- MQTT: Evaluate brokered publication when several consumers need the same events.
- HTTP: Evaluate the required web interfaces, tooling and transport before comparing costs.
The simulator comparisons become a protocol choice only after interaction pattern and device constraints are considered together. Use the figure in the parent chapter to turn those observations into a repeatable selection route.
Read the figure in the parent chapter from the interaction question at the top. Small operations on named resources lead toward CoAP when sleep cycles, UDP, and tight headers matter; brokered fan-out leads toward MQTT; a full web API and proxy ecosystem leads toward HTTP. The branches describe fit, not a universal winner. Having chosen an interaction model, the next question is what that choice costs on the wire.
Interactive Tool: CoAP Message Size Calculator
Audit a simplified byte model. It fixes CoAP token/options at eight bytes and UDP/IPv4 at 28 bytes; it does not encode the actual resource. The URI-length control changes only MQTT. HTTP includes an assumed setup cost, while MQTT setup is excluded. Security, responses, retries and link framing are omitted. If the eight-byte allowance contains only token/options, the CoAP payload marker is also missing. The displayed totals therefore are not packet captures or complete exchange costs.
At a fixed payload, identify which bytes the model counts before comparing totals. For the tank, a longer resource path can add CoAP option bytes even though this calculator leaves them fixed.
Use a capture of the intended request, response, security and retry policy to replace the model’s constants. Fewer bytes can reduce airtime under otherwise equal conditions; battery life also depends on receive, idle and sleep work.
Battery Life Calculator: CON vs NON Messages
Delivery policy changes radio work, so use the interactive battery-life calculator below before treating CON or NON as a default. Set the daily message rate first, then switch message type and compare size, daily energy, and the modeled battery-life bars.
The preserved interactive calculator uses an inconsistent 12-byte ACK allowance: its CON cards and bars are not valid UDP/IPv4 totals. For the corrected model, assume an IPv4 header without options (20 bytes), a UDP header (8 bytes), and an empty CoAP ACK (4 bytes, with no Token, options or payload). The ACK therefore adds 20 + 8 + 4 = 32 bytes to the illustrative 45-byte request, giving 77 bytes across both directions before link-layer framing, security or retries. This models one request and one empty ACK; an application response would add traffic.
At 1,000 exchanges/day, applying the calculator’s 250,000 bit/s, 20 mA and 3 V assumptions uniformly to counted bytes gives 0.0864 J/day for 45 bytes and 0.14784 J/day for 77 bytes. Dividing its assumed 2,430 J budget by these costs and by 365 gives 77.05 and 45.03 years respectively. These are equivalent transmit-energy calculations across both directions, not a device measurement: a sending device receives the ACK, and its receive current and listening time need separate accounting. The calculator’s CON output retains the old allowance; use the corrected arithmetic here rather than its CON cards or bars. Neither result forecasts product battery life.
NON vs CON Performance:
Read these points as one illustrative byte-count comparison: NON sends a 45-byte request and CON plus an empty ACK exchanges 77 bytes, a 32-byte increase under the IPv4 assumptions above. Radio energy also depends on the receive window, retries, and sleep schedule. Use CON when acknowledgment and retry matter, while planning for failure after the retry limit. This transmit-only accounting excludes receive energy, idle current, security, self-discharge and pulse capability; its years are not a service-life prediction.
- NON messages skip acknowledgment; this model counts 45 bytes versus 77 bytes for CON plus an empty ACK (32/77 ≈ 42% fewer bytes)
- CON messages request an ACK and may retry; the corrected 77-byte exchange is 32/45 ≈ 71% more than NON before retries
- Battery-life change depends on the full device energy budget
- Use CON when acknowledgment and bounded retries are needed
Checkpoint: Message Cost
You now know:
- CoAP’s base header is four bytes; the HTTP numbers here are chosen accounting assumptions.
- For the 5-byte temperature example, the chapter’s model gives 45 bytes for CoAP and 425 bytes for HTTP.
- Under the stated IPv4 assumptions, an empty ACK adds 4 CoAP + 8 UDP + 20 IPv4 = 32 bytes, giving a 77-byte request-plus-ACK model. The preserved calculator still uses 12 bytes; its CON output is inconsistent with that framing and is not a device measurement.
What This Simulates: An embedded ESP32 UDP example. The remote simulation has not been verified here; use the checks below to establish which CoAP fields it actually exposes.
Before starting the simulator, inspect the figure in the parent chapter to predict which endpoint owns each resource and which identifiers should match when the response returns.
Read the diagram in the figure in the parent chapter from the ESP32 client across UDP port 5683 to the sensor server. GET selects /temperature, while PUT targets /led; the server maps each method and path to resource behavior. On the return path, Message IDs support the exchange and Tokens correlate responses with requests. Use those predicted fields as checkpoints while the serial trace runs.
How to Use:
- Start the simulation and locate a request’s method and resource path in the serial output. Expect GET
/temperatureor PUT/ledonly if implemented; a missing path means the trace cannot verify resource dispatch. - Compare the response Token with the request Token, and an ACK’s Message ID with the acknowledged message. Missing identifiers mean correlation is unverified; UDP text alone is insufficient.
- Inspect the response code and resulting resource state. An ACK without a success response does not prove an update. Record unavailable fields rather than inferring them from elapsed time.
Multicast Support
Once a single exchange is clear, scale the same resource model to a group. Multicast helps discovery without changing what GET means.
CoAP supports multicast for group communication:
IPv4 Multicast
224.0.1.187
IPv6 Multicast
FF0X::FD
Use cases:
- Discover devices on network
- Broadcast commands to group
- Query multiple sensors simultaneously
Example:
coap://[FF05::FD]/temperature
This address identifies the example group and scope; X in the address pattern is a scope placeholder. A multicast GET is NON. Only reachable, participating servers that choose to answer contribute replies; the request does not establish that every device received it.
Multicast Efficiency Calculator
The calculator assumes 24-byte requests, 12-byte responses, and a reply from every device. Its fixed 10 ms multicast time does not include a verified collection window or paced reply delays; the displayed “faster” percentage is not a completion-time result.
Use the calculator to compare request amplification, not to assume multicast makes every operation safe. Set Number of Devices first, then switch Communication Type between Unicast (individual) and Multicast (group). Unicast increases request count and sequential time with every device; multicast holds the outbound request count at one but still receives one response per participating endpoint. That distinction explains why discovery benefits from multicast while state-changing commands still need per-device authorization, outcome tracking, and retry decisions.
Checkpoint: Discovery and Observe
You now know:
- Multicast can send one discovery request instead of contacting 50 sensors one by one.
- Polling 50 sensors every 5 seconds creates 600 request cycles per minute even when values stay stable.
- Observe can avoid unchanged-value polls, but registration lifetime, notification pacing and freshness still need checking.
CoAP Features
Return to the tank: discovery finds an advertised alarm resource, GET reads its representation, PUT sets the desired limit, and Observe can report later state changes. Each feature answers a different question. Discovery does not authorize a change, and a notification does not prove a physical alarm operated.
- Reduced Overhead: Four-byte base header, plus other fields and layers.
- URI Support: An address identifies the resource.
- Content-Format: Identifies the payload representation, such as text or JSON.
- Resource Discovery: Query
/.well-known/corefor advertised links. - Observe Pattern: Register for subsequent resource notifications.
- Caching: Max-Age describes response freshness for reuse.
- Block-wise Transfer: Transfer representations in blocks.
- Security: Configure protection and peer identity separately; UDP examples can use DTLS.
Resource Discovery
Query a known server for its advertised resources. In this example, /temperature advertises text (ct=0) and /config JSON (ct=50). Select the path and representation before issuing the operation; the listing alone proves neither permission nor implementation behavior:
GET coap://device.local/.well-known/core
Response:
</temperature>;ct=0,
</humidity>;ct=0,
</pressure>;ct=0,
</config>;ct=50
What This Simulates: An embedded discovery example whose remote behavior is unverified here. Check for the request and response rather than assuming automatic device enrollment.
Resource Discovery Flow:
Step 1: Client queries server
GET coap://device/.well-known/core
Step 2: Server responds with resource list
</temperature>;rt="sensor";if="core.s",
</humidity>;rt="sensor";if="core.s",
</led>;rt="actuator";if="core.a"
Step 3: Client accesses specific resource
GET coap://device/temperature
Response: "23.5"
How to Use:
- Start the simulation and look for a GET to
/.well-known/coreand a returned link list. Without both, discovery is not demonstrated. - Select an advertised path and inspect its attributes. Expect the request to use that path; a different path can produce a missing-resource error.
- GET the selected resource and compare the representation with its advertised format. A mismatch is a contract defect.
- If testing Observe, check that registration was accepted before expecting notifications. Silence alone cannot distinguish a stable value from a failed registration or lost connection.
Protocol Comparison
For the tank design, compare interactions before byte totals. The tables below describe this page’s UDP CoAP, HTTP over TCP, and brokered MQTT examples; they are not exhaustive transport specifications or measured benchmarks.
CoAP vs HTTP: Concrete Performance Numbers
| Feature | CoAP | HTTP | CoAP Advantage |
|---|---|---|---|
| Transport | UDP | TCP | No handshake overhead |
| Base Header Size in this example | 4 bytes | 100–200 bytes of illustrative HTTP headers | 96–98% fewer header bytes before CoAP options |
| Illustrative Total On-Wire Size | 40–60 bytes | 250–600 bytes | 76–93% fewer bytes across the stated endpoints |
| Connection Setup | None (UDP) | 3-way handshake | Saves 1+ RTT + ~180 bytes |
| Methods | GET, POST, PUT, DELETE | Same + more | Focused on IoT needs |
| Discovery | Advertised links at /.well-known/core | Depends on the application | Compare actual enrollment and discovery requirements |
| Multicast | Yes (FF0X::FD) | No | One-to-many efficiency |
| Observe | Resource notifications | Application may use Server-Sent Events | Savings depend on polling and notification policies |
| Security | DTLS | TLS | UDP-optimized |
Real Numbers Example - Temperature Reading:
Scenario: Send “22.5C” (5 bytes payload) from sensor to server
Putting Numbers to It
This is an illustrative accounting exercise, using the calculator’s incomplete framing allowance. It is not a complete on-wire capture. Here means counted overhead and means payload bytes:
CoAP message: bytes
HTTP message: bytes
Assume 1,000 daily readings, 3 V, 200 mA transmit current and 250 kbps effective link rate. These are selected model inputs, not measured ESP32 behavior; the earlier battery calculator uses 20 mA instead:
Dividing an assumed 675 mWh = 2,430 J energy budget by these transmit-only costs yields about 7.7 years versus 0.8 years. This division does not establish that a CR2032 can supply the assumed radio current. The 9.4× overhead ratio translates directly to a 9.4× difference in radio energy per day. Note: real-world battery life will be shorter due to sleep/idle current, MCU processing, and other loads; this model isolates the protocol overhead contribution.
The arithmetic above becomes easier to audit when bytes, energy, and lifetime stay on one scale. Use the figure in the parent chapter to check that each stage preserves the same overhead ratio.
Read the figure in the parent chapter from on-wire bytes to daily energy and finally to TX-only battery life. The example’s 45-versus-425-byte traffic becomes 0.86 versus 8.16 joules per day under the same radio assumptions, so the lifetime bars reverse in length. Because sleep current, computation, retries, and battery behavior are excluded, carry forward the comparative conclusion—protocol overhead matters—not the projected years as a deployment promise.

Maths · guided foundations
The Efficiency Claim Reduces to Counting Bytes
Check the quantities and assumptions.
Checkpoint: Protocol Selection
You now know:
- CoAP keeps REST-style GET, POST, PUT, and DELETE while avoiding TCP setup.
- In the chapter model, 1,000 daily readings produce 0.86 J/day for CoAP and 8.16 J/day for HTTP radio transmission.
- The isolated protocol-overhead model yields 7.7 years versus 0.8 years of TX-only battery life before other loads are counted.
CoAP vs MQTT
| Feature | CoAP | MQTT |
|---|---|---|
| Pattern | Request/Response | Publish/Subscribe |
| Transport | UDP | TCP |
| Discovery | Built-in | External |
| QoS | Via message type | 3 levels (0,1,2) |
| Broker | Optional | Required |
| Best For | RESTful IoT | Event-driven IoT |
CON and NON Pattern Evidence
Choose the CoAP message type per interaction, not per deployment. The method tells the server what operation to perform; CON or NON tells the protocol how much delivery evidence is worth paying for.
| Interaction | Prefer | Reason |
|---|---|---|
| Periodic temperature or humidity reading | NON | The next reading replaces the missing one, so avoiding ACK traffic usually matters more than perfect delivery |
User-initiated configuration PUT | CON, plus response/state checks | Retry message loss; inspect the operation response and verify the saved value |
| Door unlock, alarm, valve close, or safety threshold alert | CON, with application outcome verification | Bounded retries can still fail; missing completion must trigger the application’s failure policy |
| High-frequency heartbeat | NON, with application-level missing-heartbeat detection | Missing one heartbeat is tolerable; several missing heartbeats become the signal |
| Firmware block transfer | CON in this example, plus completeness checks | Detect missing blocks and verify the completed representation |
For constrained sensors, a hybrid policy is often the measurable answer: routine telemetry as NON, rare commands and critical alerts as CON. Record the tolerated loss rate, expected message frequency, and retry budget so the battery and reliability tradeoff can be checked in tests.
See Also
Review the method code contract first, then the message types used to carry those requests and responses.
A thermostat target is 18 C. You need it stored as 21 C, with no other writer. Your first request receives only an empty ACK; its separate response is lost. A fresh same-value request later returns 2.04 Changed, and a fresh GET returns 2.05 Content with 21 C. Which method, repeat prediction, and success report fit?
PUT /target with 21 C; a fresh identical repeat preserves 21 C. Report the stored setting after the correlated 2.04 Changed and fresh 21 C readback, not from the empty ACK alone.
Correct. PUT expresses fixed desired state, so a fresh same-value repeat preserves its intended effect. The empty ACK confirms message receipt; the correlated success response and fresh readback establish the stored setting.
A facility manager has 200 CoAP sensors from three manufacturers on the same link-local multicast scope. Each supports CoRE resource discovery, and identity enrollment is handled separately. The installer wants to discover their resource addresses without manually entering each IP. Which feature fits?
Resource discovery at /.well-known/core using a multicast query
Correct. A NON multicast GET to the link-local CoAP group at /.well-known/core can discover responses from reachable devices that implement CoRE Link Format. The client must handle missing or delayed responses, and discovery does not replace identity enrollment.
An IoT architect is designing a smart parking system. Sensors report infrequent car-presence changes and need individually addressable maintenance resources. There is no broker, and the device design requires short datagram exchanges without TCP connection setup or a persistent session. Five-year battery life remains a target to verify. Which listed protocol best fits?
CoAP for sparse device updates and individually addressable resources.
Correct. CoAP provides compact resource-oriented exchanges over UDP without a broker, fitting the stated datagram design and addressable maintenance resources. Choose CON or NON from the consequence of a missed state change, and measure whole-device energy before accepting the five-year target.
Summary
For the tank, GET reads, PUT sets a fixed alarm limit, and POST can create a calibration record. Predict a repeat’s intended effect before retrying after a lost reply. Discovery identifies candidate resources; Observe can reduce repeated reads. Neither feature establishes successful actuation. Keep response codes, correlation fields and resulting state as separate evidence.
Key Takeaway
Choose the method from the intended action, the delivery policy from the cost of loss, and the success claim from the response and verified state. Use byte models to ask what to measure, then transfer that rule to the next resource.



