Chapters

12 REST API Practice: Protocol Review

app-protocols
rest
api

Start with the story: A smart thermostat needs a web address, or URL, for its reading. A method says what the app asks it to do. A status code says how the request went; a payload is the data sent with it. These choices are part of an API, the agreed set of requests an app can make. Each worked example turns an IoT situation, such as an offline device, into a choice you can test.

12.1 Start With the Decision

This section: Start With the Decision — A soil sensor wakes every six hours and sends 15 bytes.

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 section: Route Overview — This is part 2 of 2.

This is part 2 of 2. Review REST API Practice: Design Examples for the preceding evidence.

12.3 Learning Objectives

This section: 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

This section: 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?

A successful request can return cached data with freshness metadata; clients then decide how to display an offline sensor.

  • 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:

Use 503 when the service cannot supply required live data, and include retry timing when that helps the client.

  • 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

This section: Concept Relationships — Resource identity decides when to use 404.

Understanding how REST API design concepts interconnect:

Resource identity decides when to use 404. Link cost and gateway roles guide protocol choice.

  • 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

This section: Interactive Calculators — The calculators turn the earlier examples into sliders.

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.

This section:

Broker Bex, Messaging and broker domain expertCheckpoint: 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.

This section:

12.7 Deep Dive: Reading an HTTP Message Like an Engineer

This section: Deep Dive: Reading an HTTP Message Like an Engineer — The worked examples above build whole endpoints.

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.

This section:

Broker Bex, Messaging and broker domain expertCheckpoint: 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.

This section:

12.8 See Also

This section: See Also — Review API patterns before the worked selection examples, then place the result in the wider protocol stack.

REST API Foundations:

Review API patterns before the worked selection examples, then place the result in the wider protocol stack.

Protocol Selection:

The worked selection case connects stack fundamentals to MQTT and CoAP traffic patterns.

Implementation:

Use MQTT for brokered events and CoAP for constrained exchanges when testing the REST design against device needs.

12.9 Try It Yourself

This section: 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:

The parking API must show live spots, reports, and payments. It must also show offline sensors.

  • 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:

Name resources and methods first. Then test status codes, link cost, and stale data.

  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:

Check endpoint coverage, offline status behavior, and daily HTTP versus CoAP traffic to verify the proposed API.

  • 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?

This section: 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 section: Continue Your Route — This is the last part of this chapter.

This is the last part of this chapter. Return to REST API Practice: Design Examples or continue from the Application Protocols Module Guide.

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 paths

Reviewed

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 stuck

Reviewed

How do interactive examples work?

Use the interactive guide to check how examples and simulations work before changing your project.

Interactive examples guide

Reviewed