Chapters

Resource and Response Contracts: CoAP API Design Reference

The source material below accompanies CoAP API Design: Resource and Response Contracts. Its checks have moved to the standalone check page.

Start With the Decision

A room sensor exposes /sensor/temperature for its current reading and /sensor/config for its sampling rate, meaning how often it takes a reading. A client is the program making a request; the sensor is the server answering it. The client must read without changing settings and replace a setting without accidentally requesting another action.

An application programming interface (API) defines those requests and their results. CoAP is the Constrained Application Protocol, a request and response protocol for constrained devices. A resource is a named value or state; its path identifies it. The method says what to do, the payload carries data, and the response code reports the result.

Work through one contract: GET /sensor/temperature returns 2.05 Content with the text body 23.5, interpreted as degrees Celsius by this API. PUT /sensor/config replaces the sampling-rate setting using a JSON object whose sampling_rate field is a positive number of samples per minute; a successful update returns 2.04 Changed. JSON, or JavaScript Object Notation, represents named values as text. An invalid setting returns 4.00 Bad Request without changing the stored setting. These are design choices for this example, not a complete deployed API.

Start with a stored sampling_rate of 2 samples per minute. The following values are illustrative application settings, not protocol defaults:

  1. Send PUT /sensor/config with Content-Format application/json (50) and body {"sampling_rate":6}. The field is positive, so this contract returns 2.04 Changed and stores 6 samples per minute.
  2. Send another PUT to the same resource with the same Content-Format and body {"sampling_rate":0}. Zero violates the positive-number rule, so this contract returns 4.00 Bad Request and leaves the stored rate at 6 samples per minute.
  3. Correct the body to {"sampling_rate":3} and retry PUT with Content-Format application/json (50). The valid replacement returns 2.04 Changed and stores 3 samples per minute. Retrying the unchanged zero value would still fail.

Route Overview

This is part 1 of 2. Continue with CoAP API Design: Delivery and Security Decisions.

Part Objectives

  • Map sensor operations to CoAP resources and methods.
  • Select response codes and error payloads for common failures.

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
In 60 Seconds

Read a value, replace a setting, explain a failure.

For the room sensor, use GET to read /sensor/temperature and PUT to replace /sensor/config. State the unit and payload structure before writing the client. A response code lets the client distinguish returned content, an accepted change, and a rejected request.

Repeat the same desired configuration rather than expressing “increase the rate again.” Check the stored setting afterward. The contract must say what repeated requests mean; receiving a reply alone does not prove a physical sampling result.

Choose a representation, meaning an encoding of the resource’s data, that both endpoints can decode. Compare bytes only after checking that the encodings retain the same required fields. Then transfer this rule to an LED state resource later on the page.

Phoebe’s Field Notes: Separate Annual Charge from Pulse Survival

Keep the budgets separate. A smaller payload is a byte-count result. It does not by itself establish battery lifetime or the voltage available during a radio pulse. Use the linked lesson for the separate charge and pulse calculations; neither calculation replaces the resource and response contract here.

Math Bridge · guided foundationsCan NON last longer and still brown out?Let Eddie keep annual charge and pulse voltage in two honest ledgers.

Start With the Sensor Menu

Write the room sensor’s menu as a request and expected result. Reading the temperature must leave the sampling rate alone. Replacing the configuration must return a distinguishable success or failure. Test the response code and the resulting state together.

The reusable decision is: identify the resource, choose the method, agree on the representation, then specify the response and the client’s next action.

Learning Objectives

By the end of this page, you will be able to:

  • Choose a resource and method for reading a value or replacing a setting.
  • Select an encoding that preserves the fields the client needs.
  • Predict the response to a valid request, an invalid setting, or an unsupported method.
  • Apply the same contract to a different device.
Quick Check: CoAP API Boundary

Treat the resource menu as a set of agreements. /sensor/temperature names data; GET asks to read it. /sensor/config names settings; PUT supplies their desired replacement. A path alone does not tell a client which methods or formats the server supports.

Sammy’s temperature path has one job: return the current reading. Its configuration path has another: accept a replacement sampling-rate setting. Keep the unit, field names, allowed values, and failure behavior in the contract so two clients interpret the same result alike.

A client can request a response format with the Accept option. Content-Format identifies the encoding of a message’s body. The server must support the requested representation; naming a format does not make it available. CBOR, the Concise Binary Object Representation, is a binary data format, not compressed JSON.

Short paths can reduce path bytes, but readability and stable meaning still matter. Neither a short name nor a smaller payload proves an energy saving for the whole device.

Prerequisites

Before diving into this chapter, you should be familiar with:

Continue: CoAP Resource Contract and Negotiation Design

This page connects names, methods, formats, and responses. For negotiation failures, freshness and cache validation, notification limits, and proxy mapping, continue to CoAP Resource Contract and Negotiation Design.

RESTful Resource Design

Minimum Viable Understanding: CoAP REST Design

The room sensor’s GET retrieves a reading; its PUT replaces settings. This is the resource-oriented approach called REST, or Representational State Transfer. The URI (Uniform Resource Identifier) identifies the resource; the method identifies the operation.

Prefer a stable noun such as /sensor/temperature and document GET separately. A path containing getTemperature is a naming choice, not a protocol syntax error. Noun paths make it easier to describe several methods on one resource.

Good vs. Bad Resource Design

Transfer the sensor rule to an LED, a light-emitting diode. Use /v1/led/state as the resource name. GET reads its state; PUT replaces the desired state. Repeating the same desired state should leave the same intended result, rather than toggling the light again. Verify the reported state separately from the physical light.

For the same design style:

  • GET /v1/temperature reads a temperature.
  • POST /v1/logs asks the collection to create a log entry.
  • DELETE /v1/logs/2025-01 removes that named log bucket.

These methods must be supported by the particular resource. A name like /turnOnLED hides the state model in an action name; renaming it alone would not define update or retry behavior.

URI Naming Conventions

For a gateway managing several devices, /v1/devices/temp42/reading, /v1/devices/temp42/metadata, and /v1/devices/temp42/config distinguish one device’s reading, description, and settings. The device identifier is temp42; it is not a measurement.

Use short, stable names that clients can interpret. Plural collection names and lowercase words are useful conventions. Choose nesting to express ownership rather than treating a particular depth as a CoAP limit. A version segment such as /v1/ is an optional compatibility policy, not a requirement of the protocol.

Interactive URI Analysis

Compare /sensor/temperature with a versioned device path in the existing analyzer. Its score reflects its own naming rules, not CoAP validity. Its “totalBytes” calculation counts URI text, including a fixed scheme length; it is not an encoded CoAP packet size. The simple parser does not validate every legal URI. Use it to inspect names, then review the actual resource contract.

Payload Format Selection

The room reading 23.5 is four text bytes in UTF-8, the character encoding used here. It works only if the client already knows the unit and the resource’s meaning. The JSON body {"device":"temp42","value":23.5,"unit":"C"} carries more information and is 43 bytes without extra whitespace. The existing CBOR model uses 37 bytes for those same three fields with a float64 reading, meaning a 64-bit floating-point number.

Choose between equivalent records before comparing size:

  • text/plain (Content-Format 0) suits a scalar when its meaning is agreed elsewhere.
  • application/json (50) represents structured data as inspectable text.
  • application/cbor (60) represents structured data in binary; measure the chosen encoding.
  • application/octet-stream (42) carries raw bytes whose layout must be agreed by both endpoints.

Content-Format is the numeric identifier of the body’s format. An encoding is usable only when the receiver understands both that format and the application’s fields. A smaller body that drops required fields does not satisfy the same contract.

Interactive Payload Comparison

First turn off the existing timestamp control to compare the three-field record above. Then enable it to add a timestamp, meaning the time attached to the reading. The text output still contains only the value, so it is not an equivalent four-field record. The CBOR count models text keys, a float64 reading, and a uint32 timestamp; it is not output from a CBOR encoder. Treat the counts as payload bytes, not total packet bytes or battery measurements.

Both endpoints support JSON and CBOR. For this specified four-field sensor record, the example encodings are 66 B as JSON and 52 B as CBOR. If the release goal is the smaller structured payload while retaining all four fields, which format fits?

application/cbor (Content-Format 60) - binary encoding can reduce the bytes needed for this structured sensor record.

Correct. CBOR preserves the structured record and saves 66 − 52 = 14 B per report, about 21.2% of the JSON payload; battery savings require a whole-device measurement.

For a new sensor record, measured JSON is 44 B and CBOR is 60 B, with both formats supported. Which format has the smaller encoded body here?

Use application/json, with a 44-byte body for this record.

Correct. The measured JSON representation is 16 bytes smaller.

Quick Check: Payload Format Selection

Versioning Strategy

Suppose an existing client expects GET /v1/temperature to return the scalar 23.5. A new client needs value, unit, and timestamp. This design can expose /v2/temperature with that richer record while keeping the old resource available during migration.

A version in the path makes the selected contract visible in requests and logs. It does not automatically preserve compatibility: document both schemas, keep the old behavior while its clients depend on it, and test each client against its chosen version. URI versioning is one application strategy, not a universal CoAP recommendation.

Error Handling

Return to PUT /sensor/config. If the submitted sampling-rate value is invalid, this example returns 4.00 Bad Request and retains the old setting. The client corrects its request before retrying. If a method is unsupported on that resource, return 4.05 Method Not Allowed; changing the payload alone will not enable that method.

Use the code to choose the recovery action. Add diagnostic detail for people without requiring clients to interpret a free-form sentence.

Standard Response Codes

Read each code against the operation and resource contract:

  • 2.01 Created: the request created a resource, for example POST creating a log entry.
  • 2.04 Changed: the resource changed, for example a successful configuration PUT.
  • 2.05 Content: the response carries a representation, for example the temperature GET.
  • 4.00 Bad Request: the server could not understand the request; this example also uses it for an invalid configuration payload.
  • 4.01 Unauthorized: the request lacks appropriate authorization; review credentials and permissions.
  • 4.04 Not Found: the requested resource was not found.
  • 4.05 Method Not Allowed: the method is not allowed for the resource.
  • 5.00 Internal Server Error: an unexpected server condition prevented fulfillment.

Transfer prediction: A client sends PUT to the read-only temperature resource. This contract returns 4.05, because the resource exists but does not permit the method. GET on that resource can still succeed. Do not diagnose a missing resource from an unsupported-method response.

Error Payload Format

This existing gateway diagnostic is an application example. Its five-minute age and retry_after value are illustrative policy values, not CoAP defaults. Define retry_after in seconds in the application schema; it is not a standard CoAP option. Select the response code for the actual failure, and identify the diagnostic body’s Content-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
  }
}

A proposed CBOR schema with integer keys:

Integer keys need a documented mapping; they do not identify fields by themselves. The list below is a schema sketch, not encoded bytes or a size measurement. Its shorter message and timestamp differ from the JSON example, so it is not an equivalent encoding comparison. Do not infer a measured saving from it.

  • 1 -> "SENSOR_OFFLINE"
  • 2 -> "Device offline"
  • 3 -> a timestamp with an agreed epoch and unit
  • 4 -> "temp42"
  • 5 -> 300

An actuator stores a target temperature of 20 C at /target. Its application contract permits PUT with Content-Format application/json (50) and a JSON object whose target_c is a number from 10 through 30 inclusive. A valid replacement returns 2.04 Changed; an out-of-range value returns 4.00 Bad Request without changing state. A client sends PUT /target with that Content-Format and body {“target_c”:35}, intending to set 25 C. Which response, stored state, and next request follow the contract?

4.00 Bad Request; retain 20 C; retry PUT /target with application/json (50) and body {“target_c”:25}.

Correct. PUT and application/json (50) satisfy the method and representation requirements, but 35 violates the application range. The rejection leaves 20 C stored. The corrected JSON PUT uses 25, so it returns 2.04 Changed and stores 25 C.

Continue to the Next Part

Carry the resource, allowed methods, supported formats, response codes, and expected state into CoAP API Design: Delivery and Security Decisions, which begins with Message Type Selection.

Hi, I’m Broker Bex. What do you need?

Find help

Let’s find what you need

Find a lesson or return to your module guide.

Give feedback

Help improve this chapter

Tell us what helped or what needs fixing.

Tips

Try a small next step

A few ways to get more from this chapter.

Ask AI

Continue the conversation

Take the conversation further with your preferred assistant.

AI help is available in supported modules when enabled in Settings.

No live person answers on independent study. Feedback does not promise a personal reply.

For welfare or safety concerns, follow your school’s procedures outside IoTClass.