REST API for IoT device in Raspberry Pi - Time & Space Complexity
When working with a REST API on an IoT device, it is important to understand how the time to handle requests changes as more data or requests come in.
We want to know how the program's work grows when the number of API calls or data size increases.
Analyze the time complexity of the following code snippet.
from flask import Flask, request, jsonify
app = Flask(__name__)
sensor_data = []
@app.route('/data', methods=['POST'])
def add_data():
data = request.json
sensor_data.append(data)
return jsonify({'status': 'success'})
@app.route('/data', methods=['GET'])
def get_data():
return jsonify(sensor_data)
if __name__ == '__main__':
app.run(host='0.0.0.0')
This code creates a simple REST API on the IoT device that stores sensor data sent by POST requests and returns all stored data on GET requests.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Returning all stored sensor data in the GET request involves traversing the entire
sensor_datalist. - How many times: The traversal happens once per GET request, and the time depends on how many data items are stored.
As the number of stored sensor data items grows, the time to return all data grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 data items returned |
| 100 | 100 data items returned |
| 1000 | 1000 data items returned |
Pattern observation: The time to handle a GET request grows roughly in direct proportion to the number of stored data items.
Time Complexity: O(n)
This means the time to respond grows linearly with the number of stored sensor data items.
[X] Wrong: "The GET request time stays the same no matter how much data is stored."
[OK] Correct: Because the API sends all stored data each time, more data means more work and longer response time.
Understanding how your IoT device handles growing data helps you design efficient APIs and shows you can think about performance in real projects.
"What if the GET request returned only the latest 10 data items instead of all? How would the time complexity change?"
Practice
Solution
Step 1: Understand REST API role
A REST API enables devices to communicate over a network using standard web protocols.Step 2: Identify IoT device needs
IoT devices use REST APIs to send sensor data or receive commands remotely.Final Answer:
To allow remote communication and control over the network -> Option BQuick Check:
REST API = Remote communication [OK]
- Confusing REST API with hardware speed
- Thinking REST API stores data locally
- Assuming REST API connects to display devices
Solution
Step 1: Identify common Python libraries
NumPy, Pandas, and Matplotlib are for data processing and visualization, not REST APIs.Step 2: Recognize Flask's role
Flask is a lightweight web framework used to build REST APIs easily on Raspberry Pi.Final Answer:
Flask -> Option AQuick Check:
Flask = REST API framework [OK]
- Choosing data libraries instead of web frameworks
- Confusing Flask with data analysis tools
- Assuming Matplotlib creates APIs
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/sensor')
def sensor():
data = {'temperature': 22, 'humidity': 60}
return jsonify(data)
# Assume app is running and /sensor is requestedSolution
Step 1: Understand jsonify function
jsonify converts Python dict to JSON string with correct headers for API response.Step 2: Analyze route output
The route returns JSON with keys 'temperature' and 'humidity' and their values.Final Answer:
{"temperature": 22, "humidity": 60} -> Option AQuick Check:
jsonify(dict) = JSON string [OK]
- Expecting plain text instead of JSON
- Confusing jsonify with HTML output
- Missing import of jsonify causing errors
from flask import Flask
app = Flask(__name__)
@app.route('/led/on')
def led_on():
GPIO.output(17, True)
return 'LED is ON'Solution
Step 1: Check GPIO usage
GPIO module must be imported and configured before use to control pins.Step 2: Verify code completeness
Code lacks 'import RPi.GPIO as GPIO' and GPIO setup like GPIO.setmode() and GPIO.setup().Final Answer:
Missing import and setup for GPIO module -> Option CQuick Check:
GPIO needs import and setup before use [OK]
- Assuming Flask route syntax is wrong
- Thinking return must be JSON always
- Ignoring GPIO initialization steps
Solution
Step 1: Check temperature condition logic
We want to return data only if temperature is above 25, so 'temp > 25' is correct.Step 2: Verify response format
Flask needs jsonify to return proper JSON response with correct headers.Final Answer:
Code with temp=30, condition temp > 25, and jsonify responses -> Option DQuick Check:
Use temp > 25 and jsonify for JSON response [OK]
- Using wrong temperature comparison operator
- Returning dict without jsonify causing errors
- Setting temperature below threshold incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
