Building a Flask-Powered REST API for a Smart Home Automation System

Learn how to create a simple REST API using Flask to control smart home devices like lights and thermostats. Perfect for beginners interested in home automation and Python web development.

Smart home automation is becoming increasingly popular, allowing you to control home devices such as lights, thermostats, and security systems remotely. In this tutorial, we'll build a basic REST API using Python's Flask framework. This API will allow you to turn devices on and off, and read their status. Don't worry if you're new to Flask or APIs; this guide is beginner-friendly and practical.

First, let's make sure you have Flask installed. You can install it using pip if you don't already have it:

python
pip install Flask

Next, we will create a Python script named `app.py`. This script will contain our Flask application with endpoints to control a smart light and a thermostat.

python
from flask import Flask, jsonify, request

app = Flask(__name__)

# Simulated device states
smart_home_devices = {
    'light': {'status': 'off'},
    'thermostat': {'temperature': 22}  # temperature in Celsius
}

@app.route('/light', methods=['GET'])
def get_light_status():
    """Get the current status of the light."""
    status = smart_home_devices['light']['status']
    return jsonify({'light_status': status})

@app.route('/light', methods=['POST'])
def set_light_status():
    """Turn the light on or off."""
    data = request.get_json()
    if not data or 'status' not in data:
        return jsonify({'error': 'Missing light status'}), 400
    status = data['status'].lower()
    if status not in ['on', 'off']:
        return jsonify({'error': 'Invalid status. Use "on" or "off".'}), 400
    smart_home_devices['light']['status'] = status
    return jsonify({'message': f'Light turned {status}'}), 200

@app.route('/thermostat', methods=['GET'])
def get_thermostat_temperature():
    """Get the current thermostat temperature."""
    temperature = smart_home_devices['thermostat']['temperature']
    return jsonify({'temperature': temperature})

@app.route('/thermostat', methods=['POST'])
def set_thermostat_temperature():
    """Set the thermostat temperature."""
    data = request.get_json()
    if not data or 'temperature' not in data:
        return jsonify({'error': 'Missing temperature value'}), 400
    try:
        temperature = float(data['temperature'])
    except ValueError:
        return jsonify({'error': 'Temperature must be a number'}), 400
    if temperature < 10 or temperature > 30:
        return jsonify({'error': 'Temperature must be between 10 and 30 degrees Celsius'}), 400
    smart_home_devices['thermostat']['temperature'] = temperature
    return jsonify({'message': f'Thermostat set to {temperature}°C'}), 200

if __name__ == '__main__':
    app.run(debug=True)

Let's break down what this code does:

- We import Flask and the necessary modules to handle JSON and HTTP requests. - We simulate device states with a Python dictionary `smart_home_devices`. - We create four routes: 1. `GET /light`: Returns the current status of the light (on/off). 2. `POST /light`: Accepts a JSON payload to turn the light on or off. 3. `GET /thermostat`: Returns the current thermostat temperature. 4. `POST /thermostat`: Accepts a JSON payload to set the thermostat temperature (between 10 and 30 degrees Celsius). - We provide error checking to ensure valid inputs. - The Flask app runs in debug mode for easy testing.

To test your API, you can use tools like `curl` or Postman. Here are some example commands using `curl`:

python
# Check current light status
curl http://127.0.0.1:5000/light

# Turn the light on
curl -X POST -H "Content-Type: application/json" -d '{"status":"on"}' http://127.0.0.1:5000/light

# Check thermostat temperature
curl http://127.0.0.1:5000/thermostat

# Set thermostat temperature to 25°C
curl -X POST -H "Content-Type: application/json" -d '{"temperature":25}' http://127.0.0.1:5000/thermostat

This basic API can be expanded with authentication, more devices, scheduling, or integration with real smart home hardware. For now, you have a foundation to build upon and experiment with REST APIs using Flask!

Happy coding and enjoy automating your smart home!