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.