photo of desk working on the mmocoat


Having bought a bunch of the materials I need to make my dumb wearable project and told the internet about it I now have no excuse to get started. I think the project can be reasonably broken down into 3 components; the twitter account that people can interact with, a server that exposes an API for my jacket to consume and the jacket itself.

I decided to start with the server as that’s the kind of thing I do for a living so it shouldn't be too difficult.

Regular followers of this blog will know that I'm a Pythonista and thankfully building a small API in Python is super easy with Flask.

Flask is a relatively lightweight framework for doing webby things with Python. It’s capable of building much more complicated applications and for what I need it's perfect.

To get started with Flask first install it with pip (preferably in a virtual environment).

$ pip install flask

Then create a file called something like app.py, import flask and instantiate an instance of it’s base class.

from flask import Flask
app = Flask(__name__)

Finally add an endpoint using a function decorator and return a fun value.

@app.route('/')
def hello_world():
    return 'Hello, Nerds!'

Run python app.py and point your browser at localhost:5000 and you should see whatever value you decided to return. Neat huh?

For jacket-server I want to return some JSON so to test I created a list of tuples and included the jsonify function from the Flask package. This gave me an application that looked like this:

from flask import Flask, jsonify

app = Flask(__name__)

colours = [
    {
        'id': 1,
        'colour': 'blue'
    },
    {
        'id': 2,
        'colour': 'red'
    }
]


@app.route('/', methods=['GET'])
def index():
    return "Welcome to Jacket Server, turn back or suffer your DOOM"

@app.route('/api/v1.0/get_tweets', methods=['GET'])
def get_tasks():
    return jsonify({'colours': colours[0]})

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

With this little app I am creating two endpoints. One at the root which just returns a dumb string that confirms I am a big nerd. The interesting one that provides my first (and potentially only) api endpoint which for now returns the ‘blue’ value of the test data.

Now I’ve got a framework I can build on to make my pointless wearable dream a reality. Next time I’ll get my Twitter component set up and integrate against it.


Comments

comments powered by Disqus