0
0
Raspberry Piprogramming~5 mins

Serving sensor data as JSON API in Raspberry Pi

Choose your learning style9 modes available
Introduction

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.

You want to check temperature or humidity from your Raspberry Pi on your phone.
You need to send sensor data to a web app or dashboard automatically.
You want to connect your Raspberry Pi sensors to other smart devices or services.
You want to log sensor data remotely without manually copying it.
You want to build a simple web service that shows live sensor readings.
Syntax
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.

Examples
This example returns fixed sensor values as JSON when you visit /sensor.
Raspberry Pi
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/sensor')
def sensor_data():
    data = {'temperature': 25, 'humidity': 55}
    return jsonify(data)
This example simulates sensor data with random values each time you call the API.
Raspberry Pi
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)
Sample Program

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.

Raspberry Pi
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)
OutputSuccess
Important Notes

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.

Summary

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.