Routes

Routes are used to map request URLs to callables that generate the response content. Bottle has a route() decorator to do that.

from bottle import route, run

@route('/hello')
def hello():
    return "Hello World!"

run() # This starts the HTTP server

Run this script, visit http://localhost:8080/hello and you will see “Hello World!” in your Browser.

GET, POST, HEAD, …

The route decorator has an optional keyword argument method which defaults to method='GET'. Possible values are POST, PUT, DELETE, HEAD or any other HTTP request method you want to listen to.

from bottle import route, request
@route('/form/submit', method='POST')
def form_submit():
    form_data = request.POST
    do_something(form_data)
    return "Done"

URL Parameter

You can extract parts of the URL and create dynamic routes with an easy syntax.

@route('/hello/:name')
def hello(name):
    return "Hello %s!" % name

@route('/say/:what/to/:who')
def say(what, who):
    return "You said '%s' to %s!" % (what, who)

By default, each :placeholder matches everything up to the next slash. To change that, you can add some regex:

  @route('/get_object/:id#[0-9]+#')
  def get(id):
    return "Object ID: %d" % int(id)

or even use full features regular expressions:

  @route('/get_object/(?P<id>[0-9]+)')
  def get(id):
    return "Object ID: %d" % int(id)

URL parameter remain strings, even if your route only matches digits. You have to manually cast them to the type you need.

The @validate() decorator

Bottle offers a handy decorator called validate() to check and manipulate URL parameter before they are passed to your request handler. It takes callables as keyword arguments and filters every URL Parameter through the corresponding callable.

from bottle import route, validate

@route('/validate/:i/:f/:csv')
@validate(i=int, f=float, csv=lambda x: map(int, x.strip().split(',')))
def validate_test(i, f, csv):
    return "Int: %d, Float:%f, List:%s" % (i, f, repr(csv))