Consider this simple Flask REST API code running on a Raspberry Pi controlling an LED. What will be the output when you send a GET request to /led/status?
from flask import Flask, jsonify app = Flask(__name__) led_state = False @app.route('/led/status') def led_status(): return jsonify({'led': 'on' if led_state else 'off'}) if __name__ == '__main__': app.run(host='0.0.0.0')
Look at the initial value of led_state.
The variable led_state is initially False, so the API returns {"led": "off"}.
You want to create a REST API to toggle an LED on a Raspberry Pi. Which HTTP method should you use to change the LED state?
Think about which method is used to create or change data on the server.
POST is used to send data to the server to change state, such as toggling an LED.
Examine this Flask code snippet for controlling a sensor. What error will it raise when running?
from flask import Flask, request, jsonify app = Flask(__name__) sensor_value = 0 @app.route('/sensor', methods=['POST']) def update_sensor(): data = request.json return jsonify({'sensor': sensor_value}) sensor_value = data['value'] return jsonify({'sensor': sensor_value}) if __name__ == '__main__': app.run()
Look at how sensor_value is assigned inside the function.
Assigning to sensor_value inside the function without global makes Python treat it as local, but it is referenced before assignment.
Choose the correct Flask route definition to turn on an LED when a POST request is sent to /led/on.
Check the correct keyword and data type for HTTP methods in Flask routes.
The methods argument must be a list of strings. Option A uses the correct syntax.
This Flask API returns sensor readings as JSON. How many key-value pairs are in the JSON response?
from flask import Flask, jsonify app = Flask(__name__) @app.route('/sensors') def sensors(): data = { 'temperature': 22.5, 'humidity': 45, 'pressure': 1013 } return jsonify(data) if __name__ == '__main__': app.run()
Count the keys in the data dictionary.
The dictionary has three keys: temperature, humidity, and pressure.