0

I need to Create the following... a basic web service using the RESTful design pattern to implement the following URIs:

http://localhost/hello?name=”world”

The above URI should return the following JSON-format text:

{ hello: “world” }

but I am having trouble trying to figure this out and where to place it among the code that has already been created.

#!/usr/bin/python
import json
from bson import json_util
import bottle
from bottle import route, run, request, abort

# set up URI paths for REST service
@route('/currentTime', method='GET')
def get_currentTime():
    dateString=datetime.datetime.now().strftime("%Y-%m-%d")
    timeString=datetime.datetime.now().strftime("%H:%M:%S")
    string="{\"date\":"+dateString+",\"time\":"+timeString+"}"
    return json.loads(json.dumps(string, indent=4,default=json_util.default))

if __name__ == '__main__':
    #app.run(debug=True)
    run(host='localhost', port=8080)
Stefan Becker
  • 5,695
  • 9
  • 20
  • 30
Penfold
  • 1
  • 2

1 Answers1

0

Dynamic programming is your best bet for an API.

from bottle import Bottle, get, post, request, response, route, abort, template, redirect, run
import ujson as json
import datetime
from bson import json_util

class Api(object):
    def __init__(self, request, option):
        self.option = option
        self.payload = merge_dicts(dict(request.forms), dict(request.query.decode()))

    def currentTime(self):
        dateString=datetime.datetime.now().strftime("%Y-%m-%d")
        timeString=datetime.datetime.now().strftime("%H:%M:%S")
        string="{\"date\":"+dateString+",\"time\":"+timeString+"}"
        return string

    def hello(self):
        return {'hello' : self.payload['name']}

@get('/api/<command>')
@post('/api/<command>')
@get('/api/<command>/<option>')
@post('/api/<command>/<option>')
def callapi(command = None, option = None):
    A = Api(request, option)
    func = getattr(A, "{}" .format(command), None)
    if callable(func):
        result = func()
        if result:
            if request.method == 'GET':
                response.headers['Content-Type'] = 'application/json'
                response.headers['Cache-Control'] = 'no-cache'
            return json.dumps(result, indent=4,default=json_util.default)
        else:
            return json.dumps({})

def merge_dicts(*args):
    result = {}
    for dictionary in args:
        result.update(dictionary)
    return result

if __name__ == '__main__':
    #app.run(debug=True)
    run(host='localhost', port=8080)

What this does is allows you to now simply create new functions under the class Api, and they dynamically become URL routes. You can check for post or get from within the API methods via the request if you need to. I merge the payloads from either a form or a query string so that you can accept either, and it treats at a single payload.

The option is just in case you want to more functionality to a route.

eatmeimadanish
  • 3,809
  • 1
  • 14
  • 20