Codes, Tokens, and Options: CoAP Messages 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.
The source material below accompanies the conceptual chapter. Its three knowledge checks are collected on the standalone check page.
Start With the Decision
A client asks a sensor for the resource /sensors/temp, an addressable item such as a reading. A reply arrives: does it acknowledge that message, answer that request, or do both? Decode its fields before treating the reply as evidence.
An endpoint is a participant identified by its network address and port. A Message ID identifies a message for duplicate detection and acknowledgment matching. A Token is a value chosen by the requester and echoed in the response to match that response to its request. A Code names the requested operation or its result. An option supplies a numbered detail, such as a path segment or payload format. The payload is the application content after those fields.
Your task is to decode an unfamiliar request and response, explain their match, and state what the reply proves. This page uses the CoAP-over-UDP layout described in RFC 7252.
Route Overview
This is part 2 of 3. Review CoAP Messages: Format Foundations for the preceding evidence.
Learning Objectives
- Decode a request and response into header, Token, options and payload.
- Use the Code, Message ID and Token to explain the result and match it to the request.
Chapter Roadmap
- The CoAP Message Format
- Minimum Viable Understanding: CoAP Message Structure
- The 4-Byte Fixed Header
- Message in a Bottle
- Checkpoint: Header Decisions
- CoAP Method Codes
- Idempotent Methods
- Response Codes
- Checkpoint: Methods and Codes
- Token: Request-Response Matching
- Token Security Consideration
- CoAP Options
- CBOR vs JSON for IoT
- Checkpoint: Tokens and Options
- Worked Example: Parsing a CoAP Message
- Worked Example: Decoding a GET Request
- Worked Example: GET /sensors/temp with JSON Response
- Putting Numbers to It
- Knowledge Check: Matching and Sequencing
The CoAP Message Format
Core Concept: Bytes below use hexadecimal (base 16), with two digits per byte. Read 44 01 7D 34 A1 B2 C3 D4 B7 73 65 6E 73 6F 72 73 04 74 65 6D 70 as a worked request. The first four bytes are the fixed header. 44 selects version 1, a Confirmable message (CON), and four Token bytes. 01 requests GET, meaning retrieve a resource. 7D 34 is Message ID 0x7D34.
Why It Matters: The next four bytes, A1 B2 C3 D4, are the Token. B7 introduces option 11, Uri-Path, with seven value bytes: sensors. The next option header, 04, adds zero to option 11 and takes four bytes: temp. These repeated options name /sensors/temp. No payload marker follows, so this request has no payload.
Key Takeaway: Suppose the sensor replies with header 64 45 7D 34 and the same Token. 64 selects an Acknowledgment (ACK) with four Token bytes; 45 means 2.05 Content. The matching Message ID acknowledges the CON. The echoed Token matches the response to the request. Neither field proves the sensor reading is physically correct.
Generalize from the request: locate the fixed header, then use its Token Length (TKL) to find where the options begin. In the layout below, Ver means version. JSON (JavaScript Object Notation) is a text format for structured values; CBOR (Concise Binary Object Representation) is a binary format. Max-Age specifies a freshness lifetime, and Observe is an option for requesting notifications when a resource changes.
CoAP message layout: compact fixed header followed by optional fields
4-byte fixed header
Ver, Type, TKL, Code, Message ID
Token
0-8 bytes for request-response matching
0xFF
Payload marker
Payload
Application data such as JSON, CBOR, sensor values, or firmware bytes
Header: the first four bytes establish where the Token starts.
Token: use distinct values for outstanding requests to the same endpoint.
Options: sorted numerically so each option can encode only its delta from the previous one.
Payload: present only when the message carries application content after the 0xFF marker.
Read left to right: fixed header, Token, options, then 0xFF and payload when content is present. Token Length locates the options; a marker at an option boundary locates the payload.
The 4-Byte Fixed Header
Return to 44 01 7D 34. Number bytes from zero; the four-byte header contains:
- Byte 0: Version (2 bits), Type (2 bits), and Token Length (4 bits)
- Byte 1: Code
- Bytes 2-3: Message ID
| Field | Bits | Description |
|---|---|---|
| Ver | 2 | Version (always 01 for CoAP 1.0) |
| T | 2 | Type: CON (00), NON (01), ACK (10), RST (11) |
| TKL | 4 | Token Length (0-8 bytes) |
| Code | 8 | Empty (0.00), request method, or response result |
| Message ID | 16 | For deduplication and ACK matching |
Header Fields Explained
Version (Ver): Always 01 binary (value 1) for CoAP RFC 7252.
Type (T): Determines reliability and message flow:
| Type | Binary | Name | Purpose |
|---|---|---|---|
| CON | 00 | Confirmable | Requests acknowledgment; retransmitted if needed within retry limits |
| NON | 01 | Non-confirmable | No message-layer ACK; a request can still receive a response |
| ACK | 10 | Acknowledgment | Confirms CON receipt |
| RST | 11 | Reset | Receiver could not process the message context |
Token Length (TKL): Number of token bytes (0-8). Tokens correlate responses to requests.
Code: Split the byte into class (3 bits) and detail (5 bits), written class.detail with two detail digits. The wire byte is 32 × class + detail: GET 0.01 is 0x01; Content 2.05 is decimal 69, or 0x45. The classes used below are:
| Class | Range | Meaning |
|---|---|---|
| 0 | 0.00; 0.01-0.04 | Empty message; RFC 7252 methods GET, POST, PUT, DELETE |
| 2 | 2.01-2.05 | Success responses |
| 4 | 4.00-4.15 | Client error |
| 5 | 5.00-5.04 | RFC 7252 server error codes listed below |
Message ID: 16-bit identifier for:
- Matching an ACK or RST to the message it acknowledges or rejects, using endpoint context too
- Detecting duplicates within the applicable duplicate-detection lifetime; it is not a permanent request identifier
When to Use Each Message Type: A Decision Guide
The sensor request uses CON so the client can detect missing acknowledgment and retry within the protocol’s limits. NON omits that acknowledgment. Choose according to whether a later reading can replace a lost one and what result the application needs to verify.
| IoT Scenario | Recommended Type | Rationale |
|---|---|---|
| Periodic temperature reading | NON when loss is acceptable | A later reading may replace a missed one; define a stale-data rule. |
| Firmware update chunk | CON when acknowledgment is needed | Detect loss, then verify reassembly and image integrity separately. |
| Smoke alarm triggered | CON when acknowledgment is needed | Receipt evidence helps, but retries cannot guarantee an alarm reaches a person. |
| Soil moisture on a constrained link | NON when loss is acceptable | Check link capacity and application requirements before adding retries. |
| Door lock command | CON when acknowledgment is needed | An ACK reports receipt; verify the command result and physical state separately. |
| Parking sensor heartbeat | NON when later heartbeats suffice | Define when missing readings make the device stale. |
| HVAC setpoint change | CON when acknowledgment is needed | Check the response Code for the update result; an empty ACK contains no result. |
Use CON for acknowledgment and bounded retries. Use the response Code and application evidence to judge whether the requested work succeeded.
Temperature Terry says: “The bottle’s label and the reply inside answer different questions.”
- Type: CON asks for acknowledgment; NON does not. Either kind of request can receive an application response.
- Code: GET asks to retrieve the temperature resource.
- Message ID: An ACK copies this number to acknowledge the message.
- Token: The response echoes this value to identify the request it answers.
An empty ACK says the bottle arrived. It does not contain the temperature; a later response can carry that result with the same Token and a different Message ID.
Checkpoint: Header Decisions
For the request 44 01 7D 34, predict what an empty ACK must copy before reading on.
It copies Message ID 7D 34. Its Code is 0.00 and its Token Length is zero, so it carries neither Token nor payload. This acknowledges the message while leaving the GET result pending. A NON request would not require this ACK.
CoAP Method Codes
The running request has Code 01, so the server retrieves /sensors/temp. Change that byte to 03 and the operation becomes PUT; the path alone does not determine the operation. These RFC 7252 methods use numeric codes:
| Code | Method | Description | Idempotent |
|---|---|---|---|
| 0.01 | GET | Retrieve resource | Yes |
| 0.02 | POST | Process submitted data; may create a resource | Not guaranteed |
| 0.03 | PUT | Create or replace the target resource state | Yes |
| 0.04 | DELETE | Remove resource | Yes |
An idempotent method has the same intended effect when an identical request is applied repeatedly as when it is applied once. This does not require identical response bytes:
GET /temperaturerequests a reading without asking to change state. Temperature may change between reads.PUT /led {"on": true}requests the same final state each time.DELETE /alarm/5requests removal each time; a later response can report that the resource is already absent.
POST has no general idempotence guarantee. Separate POST /log {"event": "click"} requests may append separate entries.
A CoAP retransmission repeats the same message, including its Message ID, so duplicate detection can avoid processing it again. Starting a new request after a timeout is different. Review application duplicate handling before repeating a non-idempotent operation; idempotence does not guarantee delivery or success.
Response Codes
The running response uses 0x45: 2 × 32 + 5, or 2.05 Content. First interpret class, then detail. The HTTP columns compare meanings; they are not complete proxy translation rules.
Success (2.xx)
| Code | Name | HTTP analogy | Use Case |
|---|---|---|---|
| 2.01 | Created | 201 Created | POST created new resource |
| 2.02 | Deleted | 200 OK (for DELETE) | Resource removed |
| 2.03 | Valid | 304 Not Modified | Cached response still valid |
| 2.04 | Changed | 200 OK (for PUT) | Resource updated |
| 2.05 | Content | 200 OK | GET successful with payload |
Client Error (4.xx)
| Code | Name | HTTP analogy | Cause |
|---|---|---|---|
| 4.00 | Bad Request | 400 | Malformed request |
| 4.01 | Unauthorized | 401 | Missing authentication |
| 4.03 | Forbidden | 403 | Access denied |
| 4.04 | Not Found | 404 | Resource doesn’t exist |
| 4.05 | Method Not Allowed | 405 | Wrong method for resource |
| 4.12 | Precondition Failed | 412 | A request precondition was not met |
| 4.15 | Unsupported Content-Format | 415 | Request payload format unsupported for this resource/method |
Server Error (5.xx)
Server errors mean a server or gateway could not complete the operation. 5.00 Internal Server Error reports an unexpected server condition; 5.01 Not Implemented reports missing method capability. 5.03 Service Unavailable reports temporary unavailability. For a gateway, 5.02 Bad Gateway distinguishes an invalid upstream response from the missing timely response reported by 5.04 Gateway Timeout. These Codes locate a failure; they do not alone decide whether retrying is safe.
| Code | Name | HTTP analogy | Cause |
|---|---|---|---|
| 5.00 | Internal Server Error | 500 | Unexpected server condition prevented completion |
| 5.01 | Not Implemented | 501 | Method not supported |
| 5.02 | Bad Gateway | 502 | Proxy error |
| 5.03 | Service Unavailable | 503 | Server overloaded |
| 5.04 | Gateway Timeout | 504 | Proxy timeout |
Checkpoint: Methods and Codes
Predict the wire Code for a successful PUT update of an existing resource. Would an empty ACK supply that result?
The result is 2.04 Changed, encoded as 2 × 32 + 4 = 68, or 0x44. An empty ACK has Code 0.00, so it cannot report that update result. Creation by PUT can instead return 2.01 Created; inspect the operation outcome before choosing the detail.
Token: Request-Response Matching
The running response echoes Token A1B2C3D4. If an empty ACK arrived first, a separate response would still echo that Token but use its own Message ID. Match the endpoint and Token to the pending request.
Transfer that rule to two outstanding requests. The replies below arrive in the opposite order:
Client sends: GET /temperature, Token=0xAB12, MsgID=0x5678
Client sends: GET /humidity, Token=0xCD34, MsgID=0x5679
Server sends: 2.05 Content, Token=0xCD34, "65%" (humidity response)
Server sends: 2.05 Content, Token=0xAB12, "22.5" (temperature response)
Token vs. Message ID:
| Aspect | Token | Message ID |
|---|---|---|
| Purpose | Match response to request | Deduplication, ACK matching |
| Scope | CoAP request/response matching within endpoint context | CoAP message matching within endpoint context |
| Length | 0-8 bytes (TKL field) | Fixed 16 bits |
| Persistence | Echoed in response; unchanged on retransmission | Unchanged on retransmission; separate response uses its own ID |
| Generated by | Client (the requester) | Sender of each new CON or NON message; an ACK or RST copies it |
A Token matches a response; it does not authenticate the sender. Avoid predictable tokens where they could help an attacker guess a pending request. Use an authenticated security mechanism, such as Datagram Transport Layer Security (DTLS), for peer authentication and message protection. Randomness alone does not provide either.
The Python snippet illustrates random byte generation. A complete implementation must also avoid collisions among outstanding request tokens; four random bytes are not a universal security guarantee.
# BAD: Sequential tokens
token = counter
counter += 1
# GOOD: Random tokens
import os
token = os.urandom(4)

Knowledge check · self-test
Knowledge check
Test your understanding.
CoAP Options
The sensor request repeats Uri-Path option 11 for sensors and temp. Its response uses Content-Format option 12 to identify payload encoding. An option has a number, a length and value bytes. Options appear in nondecreasing number order, including repeated numbers.
Common Options
| Option Number | Name | Encoding / length | Purpose |
|---|---|---|---|
| 3 | Uri-Host | String | Target host |
| 7 | Uri-Port | 0-2 bytes | Target port |
| 11 | Uri-Path | String | Path segments (/sensors/temp) |
| 12 | Content-Format | 0-2 bytes | Payload media type |
| 14 | Max-Age | 0-4 bytes | Freshness lifetime in seconds |
| 17 | Accept | 0-2 bytes | Acceptable response format |
| 35 | Proxy-Uri | String | For proxied requests |
Option Delta Encoding
Start the option-number accumulator at zero. In the sensor request, B7 has high nibble B (decimal 11) and low nibble 7. Add delta 11 to zero to obtain option 11, then read seven value bytes: sensors. The next header, 04, adds zero to option 11 and takes four bytes: temp. Both options are Uri-Path.
This is delta encoding: each option stores the increase from the previous option number. A nibble is four bits. The high nibble represents delta and the low nibble represents length:
- Values 0–12 encode the delta or length directly.
- Value 13 means read one extra byte and add 13.
- Value 14 means read two extra bytes as an unsigned integer and add 269.
- Value 15 is reserved and cannot encode an option delta or length.
Read any delta extension first, then any length extension, then the value bytes. At an option boundary, 0xFF marks the start of a nonempty payload rather than another option. An FF byte inside an option value is just value data.
For /sensors/temp, the encoding is B7 | "sensors" | 04 | "temp". It occupies (1 + 7) + (1 + 4) = 13 bytes, excluding header and Token. Stop at the datagram end when no payload follows; do not search beyond it for a marker.
Content-Format Codes
The Content-Format option tells the receiver how to decode the payload. In the sensor response, C1 32 means delta 12 from zero, length one, value hexadecimal 32 (decimal 50). Option 12 is Content-Format; value 50 identifies JSON (JavaScript Object Notation). The receiver can now choose its payload decoder. The table lists media types, the named formats associated with those numeric identifiers. Accept, option 17, instead expresses which response format the requester wants. The shown request has no Accept option; assume this resource is agreed to return JSON.
| Code | MIME Type | Description |
|---|---|---|
| 0 | text/plain | Simple text |
| 40 | application/link-format | Resource discovery |
| 41 | application/xml | XML data |
| 42 | application/octet-stream | Binary data |
| 47 | application/exi | Efficient XML |
| 50 | application/json | JSON data |
| 60 | application/cbor | Compact Binary (CBOR) |
CBOR (Concise Binary Object Representation) encodes structured values in binary. JSON encodes them as text. Format selection changes how payload bytes must be decoded, not which request the Token matches.
For {"device":"temp42","value":23.5,"unit":"C"}, measure the complete serialized bytes in each supported format before claiming a saving. An incomplete hexadecimal prefix cannot establish a CBOR size. Choose a format both endpoints implement; use Content-Format 50 for JSON or 60 for CBOR. Development versus production alone does not decide the choice.
Checkpoint: Tokens and Options
A response has Token A1B2C3D4 and begins its options with C1 32. Predict its request match and payload decoder.
The Token matches the pending sensor request in the same endpoint context. Starting from option number zero, delta 12 selects Content-Format, length one takes the value 32 hexadecimal, and decimal 50 selects JSON. The Token does not select a payload format; the option does.
Worked Example: Parsing a CoAP Message
Transfer the running example to an unfamiliar path and Token. Decode the following bytes before checking each step. What changes in the request, and does it carry a payload?
Worked Example: Complete Sensor Reading – CoAP vs HTTP
A CoAP client has two in-flight requests: GET /temperature (Token=0xAA, MsgID=0x0001) and GET /humidity (Token=0xBB, MsgID=0x0002). The CON for temperature times out and is retransmitted. What values should the retransmission carry?
Token=0xAA, MsgID=0x0001 (same token and message ID)
Correct! On retransmission of a CON, both the Token AND the Message ID stay the same. The same Message ID allows the server to detect and discard the duplicate; the same Token ensures the eventual response is still matched to the correct pending request.
Two CON requests use Token 0xC1 with MID 0x1001 and Token 0xD2 with MID 0x1002. Which fields identify the empty ACK for the second request?
MID 0x1002, Code 0.00 and zero-length Token on the empty ACK.
Correct. An empty ACK matches the CON by Message ID and endpoint context; Code and Token Length are both zero, so it carries no result.
You capture a CoAP packet with first byte 0x50. What can you determine about this message?
Version 1, NON type, and a zero-length Token from header 0x50.
Correct! 0x50 = 0101 0000. Ver=01 (version 1), T=01 (NON), TKL=0000 (no token). This is a Non-confirmable message with no token.
A CoAP packet begins with byte 0x64. What does its first header byte encode?
CoAP v1 ACK with TKL=4.
Correct. 0x64 has version bits 01, type bits 10, and TKL bits 0100.
Continue to the Next Part
Carry this evidence into CoAP Messages: Parsing and Validation, which begins with Label the Diagram.



