Nowadays there are mutiple web applications that need to provide an API to let the rest of the world interact with its services. One approach to achieve a fast, easy-to-develop and easy-to-use API is using REST. If you don’t know what is REST about, I recommend you this video: An introduction to REST.
This time I am using Python to develop the example. We are going to need a python web framework called Bottle which makes the creation of the REST service a piece of cake. Bottle runs with Python 2.5+ and 3.x, make sure you are using a supported version. You can download Bottle from PyPI or install it via:
pip install bottle
Code is very straight-forward. We need to import bottle route, run and request. Each time we want to map a request, all we need is to define @route(‘/map’, method=’REST_METHOD’) above the method that will manage that request. For example: @route(‘/helloworld’, method=’GET’). That would take account of /helloworld and will generate a response for that request. Also, Bottle framework provides a method to wait and attend the requests: run(). It is configurable (host, port, server name…) but if you call it without parameters it will start a server listening to localhost:8080.
As a response, we should provide the requested information in JSON or XML format. Python has libraries to make this duty easy. These formats are used because they are easy to parse.
Bottle framework has capabilities to read from Cookies, HTTP Headers and Query Variables as well. There is more information about in http://bottlepy.org/docs/dev/tutorial.html. Here, there is a little example to create the REST API:
'''
Created on 26/06/2012
@author: Héctor Veiga. hveiga.com
'''
import bottle
from bottle import route,run,request
@route('/helloworld', method='GET')
def hello():
return 'Hello World!'
# JSON format response
@route('/book/:id', method='GET')
def book():
return {'id':id, 'name':'A Game of Thrones: A Song of Ice and Fire'}
# Query string is /action?id=4&op=6. JSON format response
@route('/action')
def select_action():
action_id = request.query.id
option = request.query.op
return {'action_id':action_id, 'option':option, 'result':'200 OK'}
# Image there is a text input named 'title' and a file input name 'image'
@route('/upImage', method='POST')
def upload_image():
title = request.forms.title
image = request.files.image
if title and image and image.file:
raw_data = image.file.read()
filename = image.filename
return 'Image uploaded!'
return 'Something went wrong. Please try again'