Routing

Falcon routes incoming requests to resources based on a set of URI templates. If the path requested by the client matches the template for a given route, the request is then passed on to the associated resource for processing.

If no route matches the request, control then passes to a default responder that simply raises an instance of HTTPNotFound. Normally this will result in sending a 404 response back to the client.

Here’s a quick example to show how all the pieces fit together:

import json

import falcon

class ImagesResource(object):

    def on_get(self, req, resp):
        doc = {
            'images': [
                {
                    'href': '/images/1eaf6ef1-7f2d-4ecc-a8d5-6e8adba7cc0e.png'
                }
            ]
        }

        # Create a JSON representation of the resource
        resp.body = json.dumps(doc, ensure_ascii=False)

        # The following line can be omitted because 200 is the default
        # status returned by the framework, but it is included here to
        # illustrate how this may be overridden as needed.
        resp.status = falcon.HTTP_200

api = application = falcon.API()

images = ImagesResource()
api.add_route('/images', images)

Default Router

Falcon’s default routing engine is based on a decision tree that is first compiled into Python code, and then evaluated by the runtime.

The add_route() method is used to associate a URI template with a resource. Falcon then maps incoming requests to resources based on these templates.

Falcon’s default router uses Python classes to represent resources. In practice, these classes act as controllers in your application. They convert an incoming request into one or more internal actions, and then compose a response back to the client based on the results of those actions. (See also: Tutorial: Creating Resources)

           ┌────────────┐
request  → │            │
           │ Resource   │ ↻ Orchestrate the requested action
           │ Controller │ ↻ Compose the result
response ← │            │
           └────────────┘

Each resource class defines various “responder” methods, one for each HTTP method the resource allows. Responder names start with on_ and are named according to which HTTP method they handle, as in on_get(), on_post(), on_put(), etc.

Note

If your resource does not support a particular HTTP method, simply omit the corresponding responder and Falcon will use a default responder that raises an instance of HTTPMethodNotAllowed when that method is requested. Normally this results in sending a 405 response back to the client.

Responders must always define at least two arguments to receive Request and Response objects, respectively:

def on_post(self, req, resp):
    pass

The Request object represents the incoming HTTP request. It exposes properties and methods for examining headers, query string parameters, and other metadata associated with the request. A file-like stream object is also provided for reading any data that was included in the body of the request.

The Response object represents the application’s HTTP response to the above request. It provides properties and methods for setting status, header and body data. The Response object also exposes a dict-like context property for passing arbitrary data to hooks and middleware methods.

Note

Rather than directly manipulate the Response object, a responder may raise an instance of either HTTPError or HTTPStatus. Falcon will convert these exceptions to appropriate HTTP responses. Alternatively, you can handle them youself via add_error_handler().

In addition to the standard req and resp parameters, if the route’s template contains field expressions, any responder that desires to receive requests for that route must accept arguments named after the respective field names defined in the template.

A field expression consists of a bracketed field name. For example, given the following template:

/user/{name}

A PUT request to “/user/kgriffs” would be routed to:

def on_put(self, req, resp, name):
    pass

Because field names correspond to argument names in responder methods, they must be valid Python identifiers.

Individual path segments may contain one or more field expressions, and fields need not span the entire path segment. For example:

/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}
/serviceRoot/People('{name}')

(See also the Falcon tutorial for additional examples and a walkthough of setting up routes within the context of a sample application.)

Field Converters

Falcon’s default router supports the use of field converters to transform a URI template field value. Field converters may also perform simple input validation. For example, the following URI template uses the int converter to convert the value of tid to a Python int, but only if it has exactly eight digits:

/teams/{tid:int(8)}

If the value is malformed and can not be converted, Falcon will reject the request with a 404 response to the client.

Converters are instantiated with the argument specification given in the field expression. These specifications follow the standard Python syntax for passing arguments. For example, the comments in the following code show how a converter would be instantiated given different argument specifications in the URI template:

# IntConverter()
api.add_route(
    '/a/{some_field:int}',
    some_resource
)

# IntConverter(8)
api.add_route(
    '/b/{some_field:int(8)}',
    some_resource
)

# IntConverter(8, min=10000000)
api.add_route(
    '/c/{some_field:int(8, min=10000000)}',
    some_resource
)

Built-in Converters

Identifier Class Example
int IntConverter /teams/{tid:int(8)}
uuid UUIDConverter /diff/{left:uuid}...{right:uuid}
dt DateTimeConverter /logs/{day:dt("%Y-%m-%d")}

class falcon.routing.IntConverter(num_digits=None, min=None, max=None)[source]

Converts a field value to an int.

Identifier: int

Keyword Arguments:
 
  • num_digits (int) – Require the value to have the given number of digits.
  • min (int) – Reject the value if it is less than this number.
  • max (int) – Reject the value if it is greater than this number.
convert(value)[source]

Convert a URI template field value to another format or type.

Parameters:value (str) – Original string to convert.
Returns:
Converted field value, or None if the field
can not be converted.
Return type:object
class falcon.routing.UUIDConverter[source]

Converts a field value to a uuid.UUID.

Identifier: uuid

In order to be converted, the field value must consist of a string of 32 hexadecimal digits, as defined in RFC 4122, Section 3. Note, however, that hyphens and the URN prefix are optional.

convert(value)[source]

Convert a URI template field value to another format or type.

Parameters:value (str) – Original string to convert.
Returns:
Converted field value, or None if the field
can not be converted.
Return type:object
class falcon.routing.DateTimeConverter(format_string='%Y-%m-%dT%H:%M:%SZ')[source]

Converts a field value to a datetime.

Identifier: dt

Keyword Arguments:
 format_string (str) – String used to parse the field value into a datetime. Any format recognized by strptime() is supported (default '%Y-%m-%dT%H:%M:%SZ').
convert(value)[source]

Convert a URI template field value to another format or type.

Parameters:value (str) – Original string to convert.
Returns:
Converted field value, or None if the field
can not be converted.
Return type:object

Custom Converters

Custom converters can be registered via the converters router option. A converter is simply a class that implements the BaseConverter interface:

class falcon.routing.BaseConverter[source]

Abstract base class for URI template field converters.

convert(value)[source]

Convert a URI template field value to another format or type.

Parameters:value (str) – Original string to convert.
Returns:
Converted field value, or None if the field
can not be converted.
Return type:object

Custom Routers

A custom routing engine may be specified when instantiating falcon.API(). For example:

router = MyRouter()
api = API(router=router)

Custom routers may derive from the default CompiledRouter engine, or implement a completely different routing strategy (such as object-based routing).

A custom router is any class that implements the following interface:

class MyRouter(object):
    def add_route(self, uri_template, resource, **kwargs):
        """Adds a route between URI path template and resource.

        Args:
            uri_template (str): A URI template to use for the route
            resource (object): The resource instance to associate with
                the URI template.

        Keyword Args:
            suffix (str): Optional responder name suffix for this
                route. If a suffix is provided, Falcon will map GET
                requests to ``on_get_{suffix}()``, POST requests to
                ``on_post_{suffix}()``, etc. In this way, multiple
                closely-related routes can be mapped to the same
                resource. For example, a single resource class can
                use suffixed responders to distinguish requests for
                a single item vs. a collection of those same items.
                Another class might use a suffixed responder to handle
                a shortlink route in addition to the regular route for
                the resource.

            **kwargs (dict): Accepts any additional keyword arguments
                that were originally passed to the falcon.API.add_route()
                method. These arguments MUST be accepted via the
                double-star variadic pattern (**kwargs), and ignore any
                unrecognized or unsupported arguments.
        """

    def find(self, uri, req=None):
        """Search for a route that matches the given partial URI.

        Args:
            uri(str): The requested path to route.

        Keyword Args:
             req(Request): The Request object that will be passed to
                the routed responder. The router may use `req` to
                further differentiate the requested route. For
                example, a header may be used to determine the
                desired API version and route the request
                accordingly.

                Note:
                    The `req` keyword argument was added in version
                    1.2. To ensure backwards-compatibility, routers
                    that do not implement this argument are still
                    supported.

        Returns:
            tuple: A 4-member tuple composed of (resource, method_map,
                params, uri_template), or ``None`` if no route matches
                the requested path.

        """

Default Router

class falcon.routing.CompiledRouter[source]

Fast URI router which compiles its routing logic to Python code.

Generally you do not need to use this router class directly, as an instance is created by default when the falcon.API class is initialized.

The router treats URI paths as a tree of URI segments and searches by checking the URI one segment at a time. Instead of interpreting the route tree for each look-up, it generates inlined, bespoke Python code to perform the search, then compiles that code. This makes the route processing quite fast.

add_route(uri_template, resource, **kwargs)[source]

Adds a route between a URI path template and a resource.

This method may be overridden to customize how a route is added.

Parameters:
  • uri_template (str) – A URI template to use for the route
  • resource (object) – The resource instance to associate with the URI template.
Keyword Arguments:
 

suffix (str) – Optional responder name suffix for this route. If a suffix is provided, Falcon will map GET requests to on_get_{suffix}(), POST requests to on_post_{suffix}(), etc. In this way, multiple closely-related routes can be mapped to the same resource. For example, a single resource class can use suffixed responders to distinguish requests for a single item vs. a collection of those same items. Another class might use a suffixed responder to handle a shortlink route in addition to the regular route for the resource.

find(uri, req=None)[source]

Search for a route that matches the given partial URI.

Parameters:uri (str) – The requested path to route.
Keyword Arguments:
 req (Request) – The Request object that will be passed to the routed responder. Currently the value of this argument is ignored by CompiledRouter. Routing is based solely on the path.
Returns:
A 4-member tuple composed of (resource, method_map,
params, uri_template), or None if no route matches the requested path.
Return type:tuple
map_http_methods(resource, **kwargs)[source]

Map HTTP methods (e.g., GET, POST) to methods of a resource object.

This method is called from add_route() and may be overridden to provide a custom mapping strategy.

Parameters:resource (instance) – Object which represents a REST resource. The default maps the HTTP method GET to on_get(), POST to on_post(), etc. If any HTTP methods are not supported by your resource, simply don’t define the corresponding request handlers, and Falcon will do the right thing.
Keyword Arguments:
 suffix (str) – Optional responder name suffix for this route. If a suffix is provided, Falcon will map GET requests to on_get_{suffix}(), POST requests to on_post_{suffix}(), etc. In this way, multiple closely-related routes can be mapped to the same resource. For example, a single resource class can use suffixed responders to distinguish requests for a single item vs. a collection of those same items. Another class might use a suffixed responder to handle a shortlink route in addition to the regular route for the resource.

Routing Utilities

The falcon.routing module contains the following utilities that may be used by custom routing engines.

falcon.routing.map_http_methods(resource, suffix=None)[source]

Maps HTTP methods (e.g., GET, POST) to methods of a resource object.

Parameters:resource – An object with responder methods, following the naming convention on_*, that correspond to each method the resource supports. For example, if a resource supports GET and POST, it should define on_get(self, req, resp) and on_post(self, req, resp).
Keyword Arguments:
 suffix (str) – Optional responder name suffix for this route. If a suffix is provided, Falcon will map GET requests to on_get_{suffix}(), POST requests to on_post_{suffix}(), etc.
Returns:A mapping of HTTP methods to explicitly defined resource responders.
Return type:dict
falcon.routing.set_default_responders(method_map)[source]

Maps HTTP methods not explicitly defined on a resource to default responders.

Parameters:method_map – A dict with HTTP methods mapped to responders explicitly defined in a resource.
falcon.routing.compile_uri_template(template)[source]

Compile the given URI template string into a pattern matcher.

This function can be used to construct custom routing engines that iterate through a list of possible routes, attempting to match an incoming request against each route’s compiled regular expression.

Each field is converted to a named group, so that when a match is found, the fields can be easily extracted using re.MatchObject.groupdict().

This function does not support the more flexible templating syntax used in the default router. Only simple paths with bracketed field expressions are recognized. For example:

/
/books
/books/{isbn}
/books/{isbn}/characters
/books/{isbn}/characters/{name}

Also, note that if the template contains a trailing slash character, it will be stripped in order to normalize the routing logic.

Parameters:template (str) – The template to compile. Note that field names are restricted to ASCII a-z, A-Z, and the underscore character.
Returns:(template_field_names, template_regex)
Return type:tuple