0
0
IOT Protocolsdevops~30 mins

RESTful API design for devices in IOT Protocols - Mini Project: Build & Apply

Choose your learning style9 modes available
RESTful API Design for Devices
📖 Scenario: You are working for a smart home company. You need to create a simple RESTful API design to manage devices like lights and thermostats. This API will help the mobile app control these devices remotely.
🎯 Goal: Build a basic RESTful API design using Python Flask that can list devices, add a new device, update device status, and show device details.
📋 What You'll Learn
Create a dictionary called devices with initial device data
Add a configuration variable allowed_statuses listing valid device states
Implement API endpoints for GET all devices, POST new device, PUT update device status, and GET device by ID
Print the JSON response of the GET all devices endpoint
💡 Why This Matters
🌍 Real World
Smart home systems use RESTful APIs to let apps control devices like lights and thermostats remotely.
💼 Career
Understanding RESTful API design is essential for IoT developers and DevOps engineers managing device communication and automation.
Progress0 / 4 steps
1
Create initial device data
Create a dictionary called devices with these exact entries: 1 mapped to {'name': 'Living Room Light', 'status': 'off'} and 2 mapped to {'name': 'Thermostat', 'status': 'on'}.
IOT Protocols
Need a hint?

Use a dictionary with integer keys 1 and 2. Each value is another dictionary with keys 'name' and 'status'.

2
Add allowed device statuses configuration
Add a list called allowed_statuses containing the strings 'on' and 'off'.
IOT Protocols
Need a hint?

Define a list with two strings: 'on' and 'off'.

3
Implement core RESTful API endpoints
Using Flask, create an app with these endpoints: @app.route('/devices', methods=['GET']) to return all devices as JSON, @app.route('/devices', methods=['POST']) to add a new device with JSON body containing id, name, and status (only if status is in allowed_statuses), @app.route('/devices/<int:device_id>', methods=['PUT']) to update the status of a device by device_id, and @app.route('/devices/<int:device_id>', methods=['GET']) to get device details by device_id. Use Flask's request and jsonify. Assume from flask import Flask, request, jsonify and app = Flask(__name__) are already defined.
IOT Protocols
Need a hint?

Use Flask decorators for routes. Use request.get_json() to get JSON data. Validate status against allowed_statuses. Return JSON responses with jsonify().

4
Print all devices JSON output
Write a line to print the JSON string of the devices dictionary using Flask's jsonify and app.test_request_context() to simulate a request context. Print the JSON string of all devices.
IOT Protocols
Need a hint?

Use app.test_request_context() to create a context, then call get_devices() and print its data as text.