Python: Routing in Bottle

Python: Routing in Bottle


Bottle utilizes a powerful routing engine to link the right callback for each request.

The two basic types of routers that Bottle offers is

i) Static Routes

ii) Dynamic Routes


A route that contains one or more wildcards is considered dynamic whereas all other routes are static.


Program to add multiple routes:


A simple wildcard contains any name/entity enclosed in angular brackets (eg <name>).

The name should be unique for a given route and should form a valid python identifier because wildcards are used as keyword arguments for the request callback afterward.

Each wildcard matches one or more characters but stops when it encounters the first slash.

Example of the requests that can be accepted:

  1. hello/<priya>

  2. hello/<jaya>


And examples requests that cannot be accepted: 

  1. /hello

  2. /hello/miss/pooja



The exact behavior of the routes can be changed by using wildcard filters.

The function of the filter is to transform the matched part of the URL before it is passed to the callback function. 

Syntax for using filters are-

<name:filter> or <name:filter:config>


The following are the standard filters used:

  1. :int matches (signed) digits and converts the value to an integer.

  2. :float function is similar to :int but is used for decimal numbers.

  3. :path all characters are matched including the slash in a non-greedy way and may be used to match more than one path segment.

  4. :re[:exp] allows to give a custom regular expression in the config field. The matched value is not changed.




We can create and implement our own filters to the router. All we need is a function that returns three elements:

i) A regular expression string, 

ii) a callable to convert the URL fragment to a python value, 

iii) a callable that does the opposite. 


The filter function is called with the configuration string as the sole parameter and may parse it as required.

Example of customized filter: