Simple Client/Server RESTful Services with Python

In this article we look at creating the basics of a RESTful service and associated client, that we’ll build on later to create our home automation server

First we need to make sure we have a couple of libraries installed, specifically httplib2 and Flask. Install them using pip

sudo pip install httplib2
sudo pip install Flask

We can check they are installed with

pip list

which should display a list which includes the following

$ pip list
Flask (0.10.1)
httplib2 (0.8)

RESTFul Server

First the server, which we build using Flask

from flask import Flask, request, json
from pymongo import MongoClient

app = Flask(__name__)
mongo_client = MongoClient()
mongo_client['HomeControl'].temperature.drop ()

@app.route("/homecontrol/api/v1.0/temperature", methods=['POST'])
def api_temperature():
    if request.headers['Content-Type'] == 'text/plain':
        print (request.data)
        return 'OK', 200
    elif request.headers['Content-Type'] == 'application/json':
        print (json.dumps(request.json))
        mongo_client['HomeControl']['temperature'].insert(request.json)
        print (mongo_client['HomeControl']['temperature'].count ())
        return "OK", 200
    else:
        return "Unsupported Media Type", 415

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

For a description of how to create a RESTFul server in Flask, check out the excellent blog by Miguel Grinberg

RESTFul Client

Then a basic client that emulates our temp server

import httplib2
import json
import time
import datetime

if __name__ == '__main__':

    httplib2.debuglevel     = 0
    http                    = httplib2.Http()
    content_type_header     = "application/json"

    url = "http://127.0.0.1:5000/homecontrol/api/v1.0/temperature"

    data = {    'room':         "Living Room",
                'temp':         23.45,
                'humidity':     50.00,
                'timestamp':    str(datetime.datetime.now())
           }

    headers = {'Content-Type': content_type_header}
    print ("Posting %s" % data)

    while True:
        response, content = http.request( url,
                                          'POST',
                                          json.dumps(data),
                                          headers=headers)
        print (response)
        print (content)
        time.sleep(3)

This simple client sits in a loop posting a JSON object to our server every 3 seconds
We’ll fill out this client as time goes by, hooking it up to real temp sensors on the pi

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