Chapters

12 REST API Practice: Protocol Review

app-protocols
rest
api

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?
Quiz 2: Comprehensive Review

Scenario: Your IoT REST API receives a request for device data, but the device is offline. What HTTP status code should you return?

SituationStatus CodeResponse BodyReasoning
Device never existed404 Not Found{"error": "DEVICE_NOT_FOUND"}The resource ID is invalid
Device exists, never reported data404 Not Found{"error": "NO_DATA_AVAILABLE"}The sub-resource (readings) doesn’t exist yet
Device offline, cached data available200 OKData + metadataWe have valid (though stale) data to return
Device temporarily unreachable, no cache503 Service Unavailable{"error": "DEVICE_UNAVAILABLE", "retry_after": 60}The service exists but can’t fulfill request now
Device permanently decommissioned410 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.status field 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: 60 header 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.

Broker BexCheckpoint: 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.

SymptomRight statusDevice action
Malformed JSON body400 Bad RequestFix the payload; do not retry unchanged
Missing or expired token401 UnauthorizedRefresh credentials, then retry
Token lacks scope403 ForbiddenStop or request authorization; retrying as-is will not help
Unknown device id404 Not FoundCorrect the resource path or provisioning record
Over rate limit429 Too Many RequestsBack off and honor Retry-After
Gateway/server overloaded503 Service UnavailableRetry later with backoff and honor Retry-After

Client

Server overloaded

Malformed body

Expired token

Missing scope

Unknown resource

Over rate limit

Request failed

Client or server fault?

Which client problem?

503 + Retry-After

back off, then retry

400 Bad Request

401 Unauthorized

403 Forbidden

404 Not Found

429 Too Many Requests

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.

Broker BexCheckpoint: Message Contracts

You now know:

  • Authorization, Content-Type, Content-Length, and Location are part of the API contract, not decorative headers.
  • 400, 401, 403, 404, 429, and 503 each imply a different device action.
  • Returning 200 OK with a hidden error or 500 for 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.

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.

Implementation:

Read these points as one connected sequence: start with MQTT Fundamentals - Message queuing for IoT; and finish with CoAP Fundamentals - Constrained application protocol.

12.9 Try It Yourself

Hands-On Exercise: Design a Smart Parking REST API

Scenario: Create a REST API for a city parking system with 1,000 parking spots across 10 parking lots. Each spot has a magnetic sensor reporting occupied/vacant status.

Requirements:

Read these points as one connected sequence: start with Mobile app needs real-time spot availability; then City operators need daily/monthly occupancy reports; then Parking enforcement needs to verify payment for specific spots; and finish with System must handle sensor offline gracefully.

  • Mobile app needs real-time spot availability
  • City operators need daily/monthly occupancy reports
  • Parking enforcement needs to verify payment for specific spots
  • System must handle sensor offline gracefully

Tasks:

Read these points as one connected sequence: start with Design the resource hierarchy (parking lots, spots, sensors, reports); then Define HTTP endpoints with proper methods (GET, POST, PUT); then Specify status codes for: spot found occupied, spot not found, sensor offline; then Calculate protocol overhead: Compare HTTP vs CoAP for 1,000 sensors reporting every 30 seconds; and finish with Design offline device handling: What should GET /lots/3/spots/42/status return if sensor hasn’t reported in 2 hours?.

  1. Design the resource hierarchy (parking lots, spots, sensors, reports)
  2. Define HTTP endpoints with proper methods (GET, POST, PUT)
  3. Specify status codes for: spot found occupied, spot not found, sensor offline
  4. Calculate protocol overhead: Compare HTTP vs CoAP for 1,000 sensors reporting every 30 seconds
  5. Design offline device handling: What should GET /lots/3/spots/42/status return if sensor hasn’t reported in 2 hours?

Verification Questions:

Read these points as one connected sequence: start with How many endpoints did you define? (Hint: At least 6-8 for full CRUD operations); then Did you distinguish between “spot doesn’t exist” (404) and “sensor offline” (200 with stale data)?; and finish with What’s the daily bandwidth consumption difference between HTTP and CoAP for your design?.

  • How many endpoints did you define? (Hint: At least 6-8 for full CRUD operations)
  • Did you distinguish between “spot doesn’t exist” (404) and “sensor offline” (200 with stale data)?
  • What’s the daily bandwidth consumption difference between HTTP and CoAP for your design?

Sample Solution Sketch:

GET    /lots                          # List all parking lots
GET    /lots/{lotId}/spots            # List spots in lot
GET    /lots/{lotId}/spots/{spotId}   # Get specific spot status
PUT    /lots/{lotId}/spots/{spotId}   # Update spot (internal only)
GET    /reports/occupancy?date=...    # Occupancy reports

For offline sensors:
GET /lots/3/spots/42 → 200 OK
{
  "spot_id": 42,
  "status": "occupied",
  "last_updated": "2026-02-09T08:15:00Z",
  "sensor": {
    "status": "offline",
    "last_seen": "2026-02-09T08:15:00Z",
    "offline_duration_minutes": 120
  }
}

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.