Python REST service using Bottle

From the command line/terminal run

pip install bottle

Bottle supports a style of defining routes to functions using decorators, for example

from bottle import route, run

@route('/<name>')
def index(name):
    return f"Hello {name}"

run(host='localhost', port=8080)

HTTP Method(s)

By default a @route will respond to a GET HTTP method, but we can change to POST or be more explicit using the following

@route('/<name>', method='GET')
# or
@get('/<name>')
# or POST
@route('/<name>', method='POST')
# or
@post('/<name>')

We can combine the methods using the following

@route('/<name>', method=['GET', 'POST'])

and then within the actual function we can use the request class like this

@route('/<name>', method=['GET', 'POST'])
def index(name):
    if request.method == 'POST':
       return f"POST {name}"
    elif request.method == 'GET':
       return f"GET {name}"

    return "Unexpected"

We can also declare multiple routes to a function like this

@route('/', method=['GET', 'POST'])
@route('/<name>', method=['GET', 'POST'])
def index(name = None):
    if request.method == 'POST':
       return f"POST {name}"
    else request.method == 'GET':
       return f"GET {name}"

    return "Unexpected"

How about some JSON

Obviously JSON is the current “in vogue” format for transferring data. To return JSON instead of a simple string we can use jsonpickle, start off by installing the library using

pip install jsonpickle

We’ll add an example class for our result

class Person:
    def __init__(self):
        self.firstName = "Eddie"
        self.lastName = "Van Halen"

and our code (and additional imports) looks like this

import jsonpickle

@get('/<name>')
def index(name):
    person = Person()
    return jsonpickle.encode(person, unpicklable=False)

The unpicklable=False turns off the pickle additional information to our JSON.

Errors

We can also supply web pages, data etc. based upon HTTP errors, such as 404 errors. Assuming we changed out @get (above) to

@get(‘/name/<name>’)

now URL’s such as http://localhost:8080/PutridParrot will fail to find a matching route and if we supply an error handler for a 404 then we can return some other data, i.e.

@error(404)
def error404(error):
    return "Got a 404!"

References

Bottle: Python Web Framework