A REST API lets your IoT device talk to other devices or apps over the internet easily. It helps you control or get data from your device remotely.
REST API for IoT device in Raspberry Pi
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/status', methods=['GET']) def get_status(): return jsonify({'status': 'Device is running'}) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
Use Flask, a simple Python web framework, to create REST APIs on Raspberry Pi.
Define routes with @app.route to handle different API endpoints.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/temperature', methods=['GET']) def temperature(): temp = 25 # example sensor value return jsonify({'temperature': temp})
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/led', methods=['POST']) def control_led(): data = request.json state = data.get('state') # Here you would add code to turn LED on/off return jsonify({'led_state': state})
This program creates two API endpoints: one to get sensor data and one to control an LED. It runs on the Raspberry Pi and listens on all network interfaces.
from flask import Flask, jsonify, request app = Flask(__name__) # Simulated sensor data sensor_data = {'temperature': 22, 'humidity': 60} @app.route('/sensor', methods=['GET']) def get_sensor_data(): return jsonify(sensor_data) @app.route('/led', methods=['POST']) def set_led(): data = request.json state = data.get('state') if state not in ['on', 'off']: return jsonify({'error': 'Invalid state'}), 400 # Simulate setting LED state return jsonify({'led_state': state}) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
Make sure your Raspberry Pi and client device are on the same network or properly configured for internet access.
Use tools like Postman or curl to test your REST API endpoints.
For real devices, replace simulated data with actual sensor readings and hardware control code.
A REST API helps your IoT device communicate over the network easily.
Flask is a simple way to create REST APIs on Raspberry Pi using Python.
You can get sensor data or control hardware remotely using API endpoints.
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
