Bird
Raised Fist0
Raspberry Piprogramming~10 mins

Serving sensor data as JSON API in Raspberry Pi - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Serving sensor data as JSON API
Start Raspberry Pi
↓
Initialize Sensor
↓
Read Sensor Data
↓
Format Data as JSON
↓
Start Web Server
↓
Wait for API Request
↓
Send JSON Response
↓
Repeat Reading & Serving
The Raspberry Pi reads sensor data, formats it as JSON, and serves it via a web API on request.
Execution Sample
Raspberry Pi
import json
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/sensor')
def sensor():
    data = {'temperature': 22.5, 'humidity': 60}
    return jsonify(data)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
This code creates a simple web API that returns sensor data as JSON when '/sensor' is requested.
Execution Table
StepActionSensor Data ReadJSON DataAPI Response Sent
1Start Raspberry Pi and initialize sensorNoneNoneNo
2Read sensor data{temperature: 22.5, humidity: 60}NoneNo
3Format data as JSON{temperature: 22.5, humidity: 60}{"temperature": 22.5, "humidity": 60}No
4Wait for API request at '/sensor'{temperature: 22.5, humidity: 60}{"temperature": 22.5, "humidity": 60}No
5Receive API request{temperature: 22.5, humidity: 60}{"temperature": 22.5, "humidity": 60}No
6Send JSON response{temperature: 22.5, humidity: 60}{"temperature": 22.5, "humidity": 60}Yes
7Repeat reading and serving on next requestNext sensor readNext JSON dataNo
💡 Server runs continuously, serving JSON data on each API request.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6Final
sensor_dataNone{temperature: 22.5, humidity: 60}{temperature: 22.5, humidity: 60}{temperature: 22.5, humidity: 60}Updated on each read
json_dataNoneNone{"temperature": 22.5, "humidity": 60}{"temperature": 22.5, "humidity": 60}Updated on each read
Key Moments - 3 Insights
Why do we format sensor data as JSON before sending?
JSON is a standard format that web clients understand easily. The execution_table row 3 shows data being converted to JSON before sending.
Does the server read sensor data on every API request?
Yes, the server reads fresh sensor data before sending a response, as shown in execution_table rows 2 and 7.
What happens if no API request is made?
The server waits idle, as shown in execution_table row 4, until it receives a request to respond.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the JSON data at Step 3?
A{"temperature": 22.5, "humidity": 60}
B{temperature: 22.5, humidity: 60}
CNone
DEmpty string
💡 Hint
Check the JSON Data column at Step 3 in the execution_table.
At which step does the API response get sent?
AStep 4
BStep 6
CStep 5
DStep 7
💡 Hint
Look at the API Response Sent column in the execution_table.
If sensor data changes, which variable in variable_tracker updates?
Ajson_data only
Bsensor_data only
CBoth sensor_data and json_data
DNeither variable
💡 Hint
See variable_tracker rows for sensor_data and json_data changes.
Concept Snapshot
Serving sensor data as JSON API:
- Initialize sensor and web server
- Read sensor data
- Convert data to JSON format
- Wait for API request
- Send JSON response
- Repeat for each request
Full Transcript
This example shows how a Raspberry Pi reads sensor data and serves it as a JSON API. First, the sensor is initialized. Then the Pi reads data like temperature and humidity. This data is converted into JSON format, which is a simple text format that computers and web browsers understand. A web server runs on the Pi, waiting for requests. When a request comes to the '/sensor' URL, the server sends the JSON data as a response. This process repeats for every new request, always sending fresh sensor data.

Practice

(1/5)
1.

What is the main purpose of serving sensor data as a JSON API on a Raspberry Pi?

easy
A. To allow other devices to easily access sensor information in a standard format
B. To store sensor data only on the Raspberry Pi without sharing
C. To convert sensor data into images for display
D. To run heavy calculations on sensor data locally

Solution

  1. Step 1: Understand JSON API purpose

    A JSON API provides data in a simple, standard format that other devices can read easily.
  2. Step 2: Relate to sensor data sharing

    Serving sensor data as JSON means sharing sensor readings so other devices or apps can use them.
  3. Final Answer:

    To allow other devices to easily access sensor information in a standard format -> Option A
  4. Quick Check:

    JSON API shares sensor data easily [OK]
Hint: JSON API means sharing data in a simple format [OK]
Common Mistakes:
  • Thinking JSON API stores data only locally
  • Confusing JSON API with image or video output
  • Assuming JSON API does heavy local processing
2.

Which of the following is the correct way to import Flask in a Python script on Raspberry Pi?

?
easy
A. import flask
B. import Flask
C. from Flask import flask
D. from flask import Flask

Solution

  1. Step 1: Recall Flask import syntax

    The Flask class is imported from the flask module using: from flask import Flask
  2. Step 2: Check options for correct case and syntax

    from flask import Flask matches correct syntax and case; others have wrong case or structure.
  3. Final Answer:

    from flask import Flask -> Option D
  4. Quick Check:

    Correct Flask import uses 'from flask import Flask' [OK]
Hint: Flask class is imported with 'from flask import Flask' [OK]
Common Mistakes:
  • Using wrong capitalization like 'import Flask'
  • Importing the whole module without accessing Flask class
  • Mixing module and class names incorrectly
3.

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 running

medium
A. Error: jsonify not defined
B. {temperature: 22.5, humidity: 60}
C. {"temperature": 22.5, "humidity": 60}
D. ['temperature', 22.5, 'humidity', 60]

Solution

  1. Step 1: Understand jsonify output

    jsonify converts Python dict to JSON string with keys in quotes and proper JSON format.
  2. Step 2: Match output format

    {"temperature": 22.5, "humidity": 60} shows correct JSON string with keys and values properly formatted.
  3. Final Answer:

    {"temperature": 22.5, "humidity": 60} -> Option C
  4. Quick Check:

    jsonify returns JSON string with quoted keys [OK]
Hint: jsonify outputs JSON with quoted keys and values [OK]
Common Mistakes:
  • Forgetting quotes around keys in JSON output
  • Confusing Python dict print with JSON string
  • Assuming jsonify returns Python list
4.

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()

medium
A. json.dumps is used instead of jsonify
B. Flask app is not created correctly
C. Route decorator syntax is wrong
D. Missing import for Flask

Solution

  1. Step 1: Check JSON response method

    Flask expects jsonify to create proper response with correct headers, not json.dumps.
  2. Step 2: Identify error cause

    Using json.dumps returns a string without correct content-type, causing client issues.
  3. Final Answer:

    json.dumps is used instead of jsonify -> Option A
  4. Quick Check:

    Use jsonify, not json.dumps, for Flask JSON responses [OK]
Hint: Use jsonify for Flask JSON responses, not json.dumps [OK]
Common Mistakes:
  • Returning json.dumps output directly in Flask
  • Not importing jsonify
  • Assuming json.dumps sets response headers
5.

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()
hard
A. temp = 24.7 return jsonify({'temperature': temp})
B. temp = read_temp_sensor() return jsonify({'temperature': temp})
C. return jsonify({'temperature': read_temp_sensor})
D. return {'temperature': read_temp_sensor()} # Flask auto converts

Solution

  1. Step 1: Call sensor function inside route

    We must call read_temp_sensor() to get current value each time the route is accessed.
  2. Step 2: Return JSON response with current value

    Assign the value to a variable and pass it to jsonify to return proper JSON response.
  3. Final Answer:

    temp = read_temp_sensor() return jsonify({'temperature': temp}) -> Option B
  4. Quick Check:

    Call sensor function and jsonify result each request [OK]
Hint: Call sensor function inside route, then jsonify result [OK]
Common Mistakes:
  • Returning function object instead of calling it
  • Using fixed value instead of live sensor reading
  • Returning dict without jsonify in Flask
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard