10 CoAP API Design: Resource and Response Contracts
More
Depth: Practitioner
Progress saves as you read. Mark sections complete as you go; your progress appears in the sidebar.
10.1 Start With the Decision
This section: Start With the Decision — A field sensor can expose one value through CoAP, a compact request and response protocol.
A field sensor can expose one value through CoAP, a compact request and response protocol. An API is the set of requests another program may make. A resource path names the value to ask for; a payload carries the data; and a response code says how the request went. Those parts must form one clear contract.
10.2 Route Overview
This section: Route Overview — This is part 1 of 2.
This is part 1 of 2. Continue with CoAP API Design: Delivery and Security Decisions.
10.3 Part Objectives
This section: Part Objectives
- Map sensor operations to CoAP resources and methods.
- Select response codes and error payloads for common failures.
10.4 Chapter Roadmap
This section: Chapter Roadmap
- In 60 Seconds
- Phoebe’s Field Notes: Does the 63% Number Survive Real Battery Physics?
- Phoebe’s Field Notes: Separate Annual Charge from Pulse Survival
- Start With the Sensor Menu
- Quick Check: CoAP API Boundary
- For Beginners: CoAP API Design
- Building Sammy’s Data Menu
- Prerequisites
- Continue: CoAP Resource Contract and Negotiation Design
- RESTful Resource Design
- Minimum Viable Understanding: CoAP REST Design
- Quick Check: Payload Format Selection
- Error Handling
10.6 Learning Objectives
This section: Learning Objectives
By the end of this chapter, you will be able to:
- Design RESTful CoAP APIs: Construct resource hierarchies using nouns with proper URI conventions and versioning strategies
- Distinguish Content Formats: Compare JSON, CBOR, and text/plain payloads and select the appropriate format for constrained versus development environments
- Implement Error Handling: Apply proper CoAP response codes (2.xx/4.xx/5.xx) and construct helpful error payloads for production systems
- Configure Security Controls: Configure DTLS, rate limiting, and per-device access control for production CoAP deployments
- Calculate Energy Tradeoffs: Calculate battery life impact of CON versus NON message types and justify the selection for different IoT use cases
- Diagnose API Pitfalls: Identify and resolve common CoAP API problems such as Observe notification floods and proxy caching issues
Designing a CoAP API means deciding how IoT devices expose their data and accept commands. Think of it as creating a menu for your sensor — you define endpoints like /temperature or /status that other devices can read. Good API design makes your IoT system easy to use and understand, even for developers who have never seen your device before.
“I want other devices to read my temperature, but I also want them to set my sampling rate,” said Temperature Terry. “How do I organize all that?”
the microcontroller sketched out a plan. “You create a resource tree, Sammy! Your root is /sensor, and under it you have /sensor/temperature for reading data and /sensor/config for settings. When someone sends a GET to /sensor/temperature, they get your latest reading. When they send a PUT to /sensor/config, they can change your sampling rate.”
“Keep your URIs short!” advised the battery. “Every extra character in the path costs bytes, and CoAP packets should stay small enough to fit in a single UDP datagram. Use /temp instead of /temperature-reading-in-celsius. Every byte saved is energy saved!”
the LED added: “And don’t forget content negotiation! Some devices want your data in JSON, others in CBOR — which is like compressed JSON. Your API should let the requester choose the format using the Accept option. One sensor, multiple formats, everyone is happy!”
10.7 Prerequisites
This section: Prerequisites
Before diving into this chapter, you should be familiar with:
- CoAP Introduction - CoAP basics and REST concepts
- CoAP Message Format - Response codes and options
10.8 Continue: CoAP Resource Contract and Negotiation Design
This section: Continue: CoAP Resource Contract and Negotiation Design — The main chapter below stays focused on the API design flow: resource naming, payload choices, security, rate limits, worked examples, and implementation checks.
The main chapter below stays focused on the API design flow: resource naming, payload choices, security, rate limits, worked examples, and implementation checks. For the deeper contract behind URI/method/content-format/response-code tuples, Accept versus Content-Format negotiation, Max-Age and ETag cache behavior, Observe throttling, and HTTP-CoAP proxy mapping, continue to CoAP Resource Contract and Negotiation Design.
10.9 RESTful Resource Design
This section: RESTful Resource Design
Core Concept: CoAP follows REST principles - design resources as nouns, use HTTP-like methods as verbs. The URI identifies WHAT you’re accessing, the method specifies HOW.
Why It Matters: Consistent RESTful design makes APIs intuitive for developers, enables caching, supports proxying, and allows standard tooling to work seamlessly.
Key Takeaway: Good resource design: coap://sensor.local/v1/temperature (noun). Bad design: coap://sensor.local/getTemperature (verb in URL).
10.9.1 Good vs. Bad Resource Design
Good resource design (nouns):
coap://sensor.local/v1/temperature- read a temperature resourcecoap://sensor.local/v1/humidity- read a humidity resourcecoap://actuator.local/v1/led/state- manage LED statecoap://gateway.local/v1/config/network- update network settings
Poor resource design (verbs - avoid):
coap://sensor.local/getTemperature- verb in URLcoap://actuator.local/turnOnLED- action embedded in path
REST operations on resources:
- GET on
.../v1/temperaturereads the current value. - PUT on
.../v1/led/stateupdates the LED state. - POST on
.../v1/logscreates a new log entry. - DELETE on
.../v1/logs/2025-01removes an old log bucket.
10.9.2 URI Naming Conventions
CoAP URIs should be short (constrained bandwidth) but descriptive:
Recommended structure: host + version + resource type + device ID + subresource
Examples:
.../v1/devices/temp42/reading.../v1/devices/temp42/metadata.../v1/devices/temp42/config
Best practices:
- Version your API: use
/v1/so future changes do not break existing clients. - Use plural nouns: prefer
/devices/temp42over a singular collection name. - Keep it short: every character adds bytes on constrained links.
- Lowercase with hyphens:
/motion-sensorsstays readable and URL-safe. - Avoid deep nesting: stop around 3-4 levels;
.../devices/sensors/temp/readingis too deep.
10.9.3 Interactive URI Analysis
10.9.4 Payload Format Selection
Choose content format based on your constraints:
Read these points as one connected sequence: start with text/plain (0) - minimal bytes for a single value like "23.5"; then application/json (50) - easiest to inspect during development and debugging; then application/cbor (60) - smaller binary payload for production constrained devices; and finish with application/octet-stream (42) - raw binary only when both sides already share the schema.
text/plain(0) - minimal bytes for a single value like"23.5".application/json(50) - easiest to inspect during development and debugging.application/cbor(60) - smaller binary payload for production constrained devices.application/octet-stream(42) - raw binary only when both sides already share the schema.
Example - Temperature reading in different formats:
- Text/plain (4 bytes):
23.5 - JSON (43 bytes):
{"device":"temp42","value":23.5,"unit":"C"} - CBOR (37 bytes with a float64 value): binary map carrying the same fields
Recommendation:
- Battery sensors: Use text/plain or CBOR (minimize bytes)
- Development: Use JSON (easy debugging)
- Production: Use CBOR when both ends support it (compact, structured)
10.9.5 Interactive Payload Comparison
10.9.6 Versioning Strategy
IoT devices often run for years - plan for API evolution:
URI versioning (recommended for CoAP):
coap://sensor.local/v1/temperature- original APIcoap://sensor.local/v2/temperature- new version with metadata
Why URI versioning for IoT:
- Simple for embedded clients
- No custom header parsing needed
- Clear in logs and debugging
- Works with all CoAP libraries
Version migration example:
- v1:
GET coap://sensor.local/v1/temperaturereturns"23.5". - v2:
GET coap://sensor.local/v2/temperaturereturns a richer CBOR payload with value, unit, and timestamp. - Rollout rule: legacy devices stay on
v1while new devices adoptv2.
10.10 Error Handling
This section: Error Handling
Use proper CoAP response codes and provide helpful error payloads:
10.10.1 Standard Response Codes
2.01 Created- POST created a new resource2.04 Changed- PUT updated an existing resource2.05 Content- GET returned a payload4.00 Bad Request- request syntax or payload was invalid4.01 Unauthorized- authentication is required4.04 Not Found- resource does not exist4.05 Method Not Allowed- method does not apply to that resource5.00 Internal Server Error- server failed while handling the request
10.10.2 Error Payload Format
JSON for human readability:
{
"error": {
"code": "SENSOR_OFFLINE",
"message": "Device has not reported in 5 minutes",
"timestamp": "2025-01-15T10:30:00Z",
"device_id": "temp42",
"retry_after": 300
}
}
CBOR for production (more efficient):
1->"SENSOR_OFFLINE"2->"Device offline"3->16422594004->"temp42"5->300
10.11 Continue to the Next Part
This section: Continue to the Next Part — Carry this evidence into CoAP API Design: Delivery and Security Decisions, which begins with Message Type Selection.
Carry this evidence into CoAP API Design: Delivery and Security Decisions, which begins with Message Type Selection.
Find help
3 reviewed answers.
Where should I start in a module?
Open the module page from the sidebar to see its chapters in order. Use the module map to return to a topic you need.
Modules and pathsReviewed
What can I try when a project does not work?
Check the symptom, then work through the diagnostic steps. Keep the error message and the smallest example that reproduces it.
When you are stuckReviewed
How do interactive examples work?
Use the interactive guide to check how examples and simulations work before changing your project.
Interactive examples guideReviewed
