Serving sensor data as JSON API in Raspberry Pi - Time & Space Complexity
When serving sensor data as a JSON API on a Raspberry Pi, it is important to understand how the time to respond grows as more data or requests come in.
We want to know how the program's work changes when the amount of sensor data or number of requests increases.
Analyze the time complexity of the following code snippet.
from flask import Flask, jsonify
import random
app = Flask(__name__)
@app.route('/sensor')
def sensor_data():
data = {"temperature": random.uniform(20, 30), "humidity": random.uniform(30, 50)}
return jsonify(data)
if __name__ == '__main__':
app.run(host='0.0.0.0')
This code creates a simple web server that returns current sensor data as JSON when a user visits the /sensor URL.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Generating sensor data and creating JSON response each time the /sensor URL is requested.
- How many times: Once per request, no loops inside the handler.
Each request triggers a fixed amount of work: reading sensor values and packaging them into JSON.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 requests | About 10 times the fixed work |
| 100 requests | About 100 times the fixed work |
| 1000 requests | About 1000 times the fixed work |
Pattern observation: The work grows directly with the number of requests, but each request takes the same small amount of time.
Time Complexity: O(n)
This means the total work grows linearly with the number of requests, but each request is handled quickly and independently.
[X] Wrong: "The server does a lot more work as more requests come in at the same time."
[OK] Correct: Each request is handled separately and quickly; the server does not do extra work just because many requests exist, it just repeats the same small work for each.
Understanding how your code handles repeated requests helps you write efficient APIs and shows you can think about performance in real projects.
What if the sensor_data function collected data from 100 sensors instead of 2? How would the time complexity change?
Practice
What is the main purpose of serving sensor data as a JSON API on a Raspberry Pi?
Solution
Step 1: Understand JSON API purpose
A JSON API provides data in a simple, standard format that other devices can read easily.Step 2: Relate to sensor data sharing
Serving sensor data as JSON means sharing sensor readings so other devices or apps can use them.Final Answer:
To allow other devices to easily access sensor information in a standard format -> Option AQuick Check:
JSON API shares sensor data easily [OK]
- Thinking JSON API stores data only locally
- Confusing JSON API with image or video output
- Assuming JSON API does heavy local processing
Which of the following is the correct way to import Flask in a Python script on Raspberry Pi?
?Solution
Step 1: Recall Flask import syntax
The Flask class is imported from the flask module using: from flask import FlaskStep 2: Check options for correct case and syntax
from flask import Flask matches correct syntax and case; others have wrong case or structure.Final Answer:
from flask import Flask -> Option DQuick Check:
Correct Flask import uses 'from flask import Flask' [OK]
- Using wrong capitalization like 'import Flask'
- Importing the whole module without accessing Flask class
- Mixing module and class names incorrectly
What will be the output of this Flask route when accessed?
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/sensor')
def sensor_data():
data = {'temperature': 22.5, 'humidity': 60}
return jsonify(data)
# Assume app is runningSolution
Step 1: Understand jsonify output
jsonify converts Python dict to JSON string with keys in quotes and proper JSON format.Step 2: Match output format
{"temperature": 22.5, "humidity": 60} shows correct JSON string with keys and values properly formatted.Final Answer:
{"temperature": 22.5, "humidity": 60} -> Option CQuick Check:
jsonify returns JSON string with quoted keys [OK]
- Forgetting quotes around keys in JSON output
- Confusing Python dict print with JSON string
- Assuming jsonify returns Python list
Identify the error in this Flask code snippet that serves sensor data as JSON:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/data')
def data():
sensor = {'temp': 25}
return json.dumps(sensor)
app.run()Solution
Step 1: Check JSON response method
Flask expects jsonify to create proper response with correct headers, not json.dumps.Step 2: Identify error cause
Using json.dumps returns a string without correct content-type, causing client issues.Final Answer:
json.dumps is used instead of jsonify -> Option AQuick Check:
Use jsonify, not json.dumps, for Flask JSON responses [OK]
- Returning json.dumps output directly in Flask
- Not importing jsonify
- Assuming json.dumps sets response headers
You want to serve live temperature sensor data from a Raspberry Pi using Flask. Which approach correctly updates the JSON response with real sensor readings each time the API is called?
from flask import Flask, jsonify
app = Flask(__name__)
def read_temp_sensor():
# Returns current temperature reading
return 24.7
@app.route('/temp')
def temp():
# Fill in here
app.run()Solution
Step 1: Call sensor function inside route
We must call read_temp_sensor() to get current value each time the route is accessed.Step 2: Return JSON response with current value
Assign the value to a variable and pass it to jsonify to return proper JSON response.Final Answer:
temp = read_temp_sensor() return jsonify({'temperature': temp}) -> Option BQuick Check:
Call sensor function and jsonify result each request [OK]
- Returning function object instead of calling it
- Using fixed value instead of live sensor reading
- Returning dict without jsonify in Flask
Ready to prove it?
Pass the test and this pattern moves unknown
