12 REST API Practice: Protocol Review
Start with the story: The design rules become real when you have to choose the exact URL, method, status code, and payload for a smart thermostat or offline device. Each worked example turns an IoT situation into an API decision you can test.
12.1 Start With the Decision
A soil sensor wakes every six hours and sends 15 bytes. Compare CoAP and MQTT to protect its two-year battery target.
12.2 Route Overview
This is part 2 of 2. Review REST API Practice: Design Examples for the preceding evidence.
12.3 Learning Objectives
- Test quiz 2: comprehensive review with a concrete scenario and pass criteria.
- Define hands-on exercise: design a smart parking rest api with explicit inputs, errors, and change rules.
12.4 Chapter Roadmap
- Quiz 2: Comprehensive Review
- Decision Framework: When to Return 404 vs 503 vs 200 with Stale Data
- Concept Relationships
- Interactive Calculators
- Checkpoint: Scaling the Numbers
- Deep Dive: Reading an HTTP Message Like an Engineer
- Checkpoint: Message Contracts
- See Also
- Try It Yourself
- Hands-On Exercise: Design a Smart Parking REST API
- What’s Next?
Scenario: Your IoT REST API receives a request for device data, but the device is offline. What HTTP status code should you return?
| Situation | Status Code | Response Body | Reasoning |
|---|---|---|---|
| Device never existed | 404 Not Found | {"error": "DEVICE_NOT_FOUND"} | The resource ID is invalid |
| Device exists, never reported data | 404 Not Found | {"error": "NO_DATA_AVAILABLE"} | The sub-resource (readings) doesn’t exist yet |
| Device offline, cached data available | 200 OK | Data + metadata | We have valid (though stale) data to return |
| Device temporarily unreachable, no cache | 503 Service Unavailable | {"error": "DEVICE_UNAVAILABLE", "retry_after": 60} | The service exists but can’t fulfill request now |
| Device permanently decommissioned | 410 Gone | {"error": "DEVICE_DECOMMISSIONED"} | The resource existed but no longer does |
Example response for offline device with cached data:
GET /api/v1/devices/sensor-042/temperature
Response: 200 OK
{
"device_id": "sensor-042",
"temperature_celsius": 22.5,
"timestamp": "2026-02-07T14:30:00Z",
"connectivity": {
"status": "offline",
"last_seen": "2026-02-07T14:30:00Z",
"offline_duration_seconds": 3600,
"data_freshness": "stale"
}
}
Why 200 OK for stale data?
Read these points as one connected sequence: start with The API request was successful — we returned valid temperature data; then The client can use the connectivity.status field to decide how to handle staleness; then Mobile apps can display “Last updated 1 hour ago” without treating it as an error; and finish with Offline devices are expected in IoT — not an error condition.
- The API request was successful — we returned valid temperature data
- The client can use the
connectivity.statusfield to decide how to handle staleness - Mobile apps can display “Last updated 1 hour ago” without treating it as an error
- Offline devices are expected in IoT — not an error condition
When to use 503 Service Unavailable:
Read these points as one connected sequence: start with Device is online but unresponsive (hung firmware); then No cached data available and request requires live data; then Cloud gateway can’t reach device network (network partition); and finish with Include Retry-After: 60 header to suggest retry timing.
- Device is online but unresponsive (hung firmware)
- No cached data available and request requires live data
- Cloud gateway can’t reach device network (network partition)
- Include
Retry-After: 60header to suggest retry timing
Key principle: IoT APIs should distinguish between “resource doesn’t exist” (404), “resource exists but unavailable” (503), and “resource available but data is stale” (200 with metadata).
12.5 Concept Relationships
Understanding how REST API design concepts interconnect:
Read these points as one connected sequence: start with Resource hierarchies determine endpoint structure, which directly impacts HTTP status code selection (404 vs 503 for missing resources); then Protocol overhead calculations (CoAP vs MQTT battery impact) inform protocol selection decisions for battery-powered deployments; then Hybrid architectures (CoAP local + MQTT cloud) leverage strengths of both request-response and publish-subscribe patterns; and finish with Offline device handling requires distinguishing between no data (404) and stale data (200 with metadata), a pattern that extends to all IoT REST APIs.
- Resource hierarchies determine endpoint structure, which directly impacts HTTP status code selection (404 vs 503 for missing resources)
- Protocol overhead calculations (CoAP vs MQTT battery impact) inform protocol selection decisions for battery-powered deployments
- Hybrid architectures (CoAP local + MQTT cloud) leverage strengths of both request-response and publish-subscribe patterns
- Offline device handling requires distinguishing between no data (404) and stale data (200 with metadata), a pattern that extends to all IoT REST APIs
12.6 Interactive Calculators
The calculators turn the earlier examples into sliders. Use them after the quizzes to check whether an API shape still works when device count, report interval, payload size, or battery capacity changes.
12.6.1 REST API Request Load Calculator
Estimate the API request rate and daily bandwidth for your IoT device fleet.
12.6.2 Protocol Overhead Comparison Calculator
Compare the overhead percentage for CoAP, MQTT, and HTTP when sending small IoT payloads.
12.6.3 IoT Battery Life Estimator
Estimate battery life based on protocol choice, transmission frequency, and battery capacity.
12.6.4 REST API Response Size Estimator
Calculate the size of JSON API responses with device metadata and connectivity status fields.
12.6.5 Fleet Bandwidth Planner
Use the planner to test when fleet growth invalidates an API capacity assumption. Set Current fleet size and Message interval first because together they determine requests per second; then change Average message size to expose the payload contribution to daily traffic. Apply Annual growth rate and Projection years last, and compare the Devices, Req/sec, Daily (GB), and Monthly (GB) outputs year by year. The result belongs in the deployment record alongside headroom and a review trigger, rather than being treated as a permanent forecast.
Checkpoint: Scaling the Numbers
You now know:
- Request rate comes from device count divided by report interval, so growth can break an API before the endpoint design changes.
- Payload and header bytes both matter; the thermostat example combined 250 bytes of HTTP overhead with 120 bytes of JSON payload.
- Battery estimates depend on radio-on time as well as protocol headers, which is why a small byte saving may still matter in a sleep-heavy device.
12.7 Deep Dive: Reading an HTTP Message Like an Engineer
The worked examples above build whole endpoints. This layered walkthrough zooms into a single message on the wire: what the status-code classes promise, what each header in a request and response is doing, and how to choose the status code that tells a device exactly what to do next.
A REST response is a control signal for firmware, not just a message for a dashboard. The first digit of the status code sets the device action: 2xx means the request succeeded, 3xx means use a different or cached representation, 4xx means the client must change something, and 5xx means the server or upstream path failed. The exact code refines that action. For example, 202 Accepted fits a command queued for a sleeping device, while 204 No Content would falsely imply the action already completed.
Here is the device-registration exchange as a contract rather than a snippet:
POST /v1/devices HTTP/1.1
Host: api.example
Authorization: Bearer eyJhbGciOi...
Content-Type: application/json
Content-Length: 40
{"name":"gh2-temp","type":"temperature"}
HTTP/1.1 201 Created
Location: /v1/devices/42
Content-Type: application/json
Content-Length: 48
{"id":42,"name":"gh2-temp","type":"temperature"}
Authorization proves who is calling before anything is created. Content-Type tells the server and client how to parse the body. Content-Length must match the actual byte count so parsers can detect truncation or smuggling mistakes. Location is the authoritative URL for the new resource; the device should persist /v1/devices/42 instead of guessing its assigned identifier.
| Symptom | Right status | Device action |
|---|---|---|
| Malformed JSON body | 400 Bad Request | Fix the payload; do not retry unchanged |
| Missing or expired token | 401 Unauthorized | Refresh credentials, then retry |
| Token lacks scope | 403 Forbidden | Stop or request authorization; retrying as-is will not help |
| Unknown device id | 404 Not Found | Correct the resource path or provisioning record |
| Over rate limit | 429 Too Many Requests | Back off and honor Retry-After |
| Gateway/server overloaded | 503 Service Unavailable | Retry later with backoff and honor Retry-After |
The two fleet-scale traps are status masking and retry amplification. Returning 200 OK with an error buried in the body tells caches, proxies, client libraries, and dashboards that the request succeeded. Returning 500 for a bad client payload makes devices retry a request that can never succeed. For sleeping or overloaded infrastructure, 503 Service Unavailable plus Retry-After: 300 turns a thundering-herd retry loop into an orderly wait.
For each worked example, write the status code beside the expected firmware action: retry now, retry after delay, refresh credential, change payload, re-provision resource, or stop. That line is the API contract devices actually execute.
Checkpoint: Message Contracts
You now know:
Authorization,Content-Type,Content-Length, andLocationare part of the API contract, not decorative headers.400,401,403,404,429, and503each imply a different device action.- Returning
200 OKwith a hidden error or500for bad input can amplify retries across a fleet.
12.8 See Also
REST API Foundations:
Read these points as one connected sequence: start with REST API Design Patterns - Versioning, payload formats, rate limiting; and finish with Application Protocols Overview - CoAP, MQTT, HTTP comparison.
- REST API Design Patterns - Versioning, payload formats, rate limiting
- Application Protocols Overview - CoAP, MQTT, HTTP comparison
Protocol Selection:
Read these points as one connected sequence: start with Protocol Selection Worked Examples - Agricultural sensor network case study; and finish with IoT Protocols Fundamentals - Protocol stack overview.
- Protocol Selection Worked Examples - Agricultural sensor network case study
- IoT Protocols Fundamentals - Protocol stack overview
Implementation:
Read these points as one connected sequence: start with MQTT Fundamentals - Message queuing for IoT; and finish with CoAP Fundamentals - Constrained application protocol.
- MQTT Fundamentals - Message queuing for IoT
- CoAP Fundamentals - Constrained application protocol
12.9 Try It Yourself
12.10 What’s Next?
-
REST API Design Patterns Focus: Versioning, payload formats, pagination, rate limiting Why read it: Apply the design principles from this chapter to build production-ready API contracts
-
Application Protocols Overview Focus: Side-by-side comparison of CoAP, MQTT, and HTTP Why read it: Deepen the protocol selection skills practised in the quizzes above
-
Protocol Selection Worked Examples Focus: Agricultural sensor network end-to-end case study Why read it: See a full deployment decision from sensor hardware to cloud using the same frameworks
-
Real-Time Protocol Workflows Focus: VoIP, SIP, RTP for audio/video IoT Why read it: Extend your protocol knowledge to streaming and real-time communication patterns
-
MQTT Fundamentals Focus: Broker architecture, QoS levels, topic design Why read it: Implement the MQTT cloud-reporting leg of the hybrid architectures covered here
-
CoAP Fundamentals and Architecture Focus: CON/NON messages, observe, block transfer Why read it: Implement the CoAP local-control leg and understand the confirmable message reliability model
12.11 Continue Your Route
This final part closes the route from Quiz 2: Comprehensive Review through What’s Next?. Return to REST API Practice: Design Examples or continue from the app-protocols module index.
