restful api

This is a basic guide to getting going with RESTFUL API's. I am not sure why it has taken me so long to get to understand these things - but better late than never :)

Python Environment

I will create a new and clean python env for this and install some basic python modules.

cd
pyvenv3.4 pyflask
source ~/pyflask/bin/activate
pip install --upgrade pip flask flask-restful 

And we are done

Dev Files

I'll put the code into a directory

mkdir ~/rest_01
cd ~/rest_01

And now we create a very simple python server script, which will act as a reminder or a todo list. This file I have called server.py

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

todos = {}

class TodoSimple(Resource):
    def get(self, todo_id):
        if todo_id in todos:
           return {todo_id: todos[todo_id]}
        else:
           return {todo_id:'Not Found'}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

    def delete(self, todo_id):
        if todo_id in todos:
           del todos[todo_id]
           return '', 204
        else:
           return {todo_id:'Not Found'}


api.add_resource(TodoSimple, '/<string:todo_id>')

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

Makefile for testing

To save typing and lots of dumb .sh files I also create a makefile.

test:
        curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT
        curl http://localhost:5000/todo2 -d "data=Feed the dog"      -X PUT
        curl http://localhost:5000/todo3 -d "data=Buy some cheese"   -X PUT
        curl http://localhost:5000/todo1 
        curl http://localhost:5000/todo3


add:
        curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT
        curl http://localhost:5000/todo2 -d "data=Feed the dog"      -X PUT
        curl http://localhost:5000/todo3 -d "data=Buy some cheese"   -X PUT


query:
        curl http://localhost:5000/todo1 
        curl http://localhost:5000/todo2
        curl http://localhost:5000/todo3


delete:
        curl http://localhost:5000/todo2 -X DELETE -v

Running & Testing

We need 2 terminal windows.

  • In both windows type
    • source ~/pyflask/bin/activate
  • In 1 Window
    • python ./server.py
  • In other Window
    • make test
    • make query
    • make delete

We have now tested the API and the web service - you can also access this service via a URL/Web Browser.