Implement bottle.py using local server

Bottle.py is a great framework for building lightweight server applications in applications – specially for API’s. Here’s how you could build a REST Framework in bottle.py that takes the payload or method invoked and does the underlying implementation:

from bottle import Bottle, run, template, get, post, request, response
import json

app = Bottle()

@app.get('/yourpath')
@app.get('/yourpath/')
@app.get('/yourpath/')
def invoke(api='Invalid-API-Call'):
apiCalled=api.lower()
#return template('GET :: Invoking {{qname}}', qname=api-name)
if(apiCalled == "create-account"):
  returnMessage = "Execute create_account()"
elif(apiCalled == "modify-account"):
  returnMessage = "Execute modify_account()"
elif(apiCalled == "delete-account"):
  returnMessage = "Execute delete_account()"
else:
  returnMessage = '{"Code" : -1, "Message" : "Invalid API Call"}'

return returnMessage

@app.post('/yourpath')
@app.post('/yourpath/')
@app.post('/yourpath/')
def invoke(api='Invalid-API-Call'):
response.content_type = 'application/json'
apiCalled = api.lower()
data = request.json #This is unicode text (decoded/dictionary)
jsonData = json.dumps(data) #Converts to JSON
if(apiCalled == "create-account"):
  returnMessage = __create_account(jsonData)
elif(api == "modify-account"):
  returnMessage = __modify_account(jsonData)
elif(api == "delete-account"):
  returnMessage = __delete_account(jsonData)
else:
  returnMessage = '{"Code" : -1, "Message" : "Invalid API Call"}'

return returnMessage

def __create_account(reqData):
  h = businessHandler(reqData)
  response = h.createAccount()
  return response

def __modify_account(reqData):
  h = businessHandler(reqData)
  response = h.modifyAccount()
  return response

def __delete_account(reqData):
  h = businessHandler(reqData)
  response = h.deleteAccount()
  return response

run(app, host='0.0.0.0', port=8081, debug=True)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s