Let's make the world a better place using digital technologies!

Create REST Service on Raspberry Pi with Flask

Creating the REST script using Flask

  • First install Flask on raspi:
pip3 install flask
  • Create a REST service using the following code. This is a very simple service that provides one command. In addition, I’ve created another interface also for providing psutil functions, as a demo.
# Script to provide a rest interface to raspberry 
# Author: Dr. Asif Rana (aiqbalrana@gmail.com) 
# License: MIT License
# Date: 20180217 
 
from flask import Flask, url_for 
import os 
import sys 
import psutil 
 
raspicmds = { 
 'reboot' : '/sbin/reboot' 
 } 
 
app = Flask(__name__) 
 
@app.route('/osinfo/<cmd>', methods=['GET', 'POST']) 
def api_osinfo(cmd): 
 cmdstr = 'psutil.' + cmd 
 cmdresp = eval(cmdstr) 
 return str(cmdresp) 
 
@app.route('/raspi/<kcmd>', methods=['GET', 'POST']) 
def api_raspicmd(kcmd): 
 if kcmd in raspicmds: 
 os.system("sudo " + raspicmds[kcmd]) 
 return str(kcmd + 'executed') 
 
if __name__ == '__main__': 
 app.run(debug=True, host='0.0.0.0') 
  • Caution: do not expose your raspi to the internet without taking good care of security. This example is just for illustration purposes.
  • Making the script a service (daemon)

  • Create this file: /lib/systemd/system/raspirest.service with following contents:
[Unit]
Description=Raspi REST Interface
[Service]
Type=simple
ExecStart=/usr/src/scripts/raspirest.py
[Install]
WantedBy=multi-user.target
  • Add and enable the service to start at boot:
sudo systemctl daemon-reload
sudo systemctl enable raspirest
  • Check if the service is running by calling it at: http://IP:Port/raspi/<yourcmd>

Asif

http://things.m31.ch

View more posts from this author

Leave a Reply

Your email address will not be published. Required fields are marked *