We want to share sensor readings from a Raspberry Pi so other devices or apps can use them easily. Serving data as a JSON API makes it simple and clear to get this information over the internet.
Serving sensor data as JSON API in Raspberry Pi
from flask import Flask, jsonify app = Flask(__name__) @app.route('/sensor') def sensor_data(): data = {'temperature': 22.5, 'humidity': 60} return jsonify(data) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
Use Flask to create a small web server on your Raspberry Pi.
The @app.route decorator sets the URL path for the API.
/sensor.from flask import Flask, jsonify app = Flask(__name__) @app.route('/sensor') def sensor_data(): data = {'temperature': 25, 'humidity': 55} return jsonify(data)
from flask import Flask, jsonify import random app = Flask(__name__) @app.route('/sensor') def sensor_data(): data = {'temperature': random.uniform(20, 30), 'humidity': random.randint(40, 70)} return jsonify(data)
This program creates a simple web server on your Raspberry Pi. When you open http://your-pi-ip:5000/sensor in a browser or app, it shows current sensor data as JSON.
from flask import Flask, jsonify import random app = Flask(__name__) @app.route('/sensor') def sensor_data(): # Simulate reading from sensors temperature = round(random.uniform(20.0, 25.0), 1) humidity = random.randint(40, 60) data = {'temperature': temperature, 'humidity': humidity} return jsonify(data) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
Make sure Flask is installed on your Raspberry Pi: pip install flask.
Replace the simulated sensor values with real sensor readings from your hardware.
Run the program and access the API from other devices on the same network using your Pi's IP address.
Serving sensor data as a JSON API lets other devices easily get your Raspberry Pi's sensor info.
Flask is a simple way to create this API with just a few lines of code.
You can start with fixed or random data, then connect real sensors later.