Routing

Falcon uses resource-based routing to encourage a RESTful architectural style. Each resource is represented by a class that is responsible for handling all of the HTTP methods that the resource supports.

For each HTTP method supported by the resource, the class implements a corresponding Python method with a name that starts with on_ and ends in the lowercased HTTP method name (e.g., on_get(), on_patch(), on_delete(), etc.)

Note

Resources in Falcon are represented by a single class instance that is created at application startup when the routes are configured. This minimizes routing overhead and simplifies the implementation of resource classes. In the case of WSGI apps, this also means that resource classes must be implemented in a thread-safe manner (see also: Is Falcon thread-safe?).

Falcon routes incoming requests (including WebSocket handshakes) 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.

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

import json

import falcon


class ImagesResource:

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

        # Create a JSON representation of the resource; this could
        #   also be done automatically by assigning to resp.media
        resp.text = 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


app = falcon.App()

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

If no route matches the request, control then passes to a default responder that simply raises an instance of HTTPRouteNotFound. By default, this error will be rendered as a 404 response for a regular HTTP request, and a 403 response with a 3404 close code for a WebSocket handshake. This behavior can be modified by adding a custom error handler (see also this FAQ topic).

On the other hand, if a route is matched but the resource does not implement a responder for the requested HTTP method, the framework invokes a default responder that raises an instance of HTTPMethodNotAllowed. This class will be rendered by default as a 405 response for a regular HTTP request, and a 403 response with a 3405 close code for a WebSocket handshake.

Falcon also provides a default responder for OPTIONS requests that takes into account which methods are implemented for the target resource.

Default Behavior

Falcon’s default routing engine is based on a decision tree that is first compiled into Python code, and then evaluated by the runtime. By default, the decision tree is compiled only when the router handles the first request. See CompiledRouter for more details.

The falcon.App.add_route() and falcon.asgi.App.add_route() methods are 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

For ASGI apps, the responder must be a coroutine function:

async 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 yourself 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 cause the framework to invoke the on_put() responder method on the route’s resource class, passing 'kgriffs' via an additional name argument defined by the responder:

# Template fields correspond to named arguments or keyword
#   arguments, following the usual req and resp args.
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 walkthrough 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()
app.add_route(
    '/a/{some_field:int}',
    some_resource
)

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

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

(See also how UUIDConverter is used in Falcon’s ASGI tutorial: Images Resource(s).)

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.

abstract 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.App() or falcon.asgi.App(). For example:

router = MyRouter()
app = App(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:
    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.App.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.

        """

Suffixed Responders

While Falcon encourages the REST architectural style, it is flexible enough to accomodate other paradigms. Consider the task of building an API for a calculator which can both add and subtract two numbers. You could implement the following:

class Add():
    def on_get(self, req, resp):
        resp.text = str(req.get_param_as_int('x') + req.get_param_as_int('y'))
        resp.status = falcon.HTTP_200


class Subtract():
    def on_get(self, req, resp):
        resp.text = str(req.get_param_as_int('x') - req.get_param_as_int('y'))
        resp.status = falcon.HTTP_200


add = Add()
subtract = Subtract()
app = falcon.App()
app.add_route('/add', add)
app.add_route('/subtract', subtract)

However, this approach highlights a situation in which grouping by resource may not make sense for your domain. In this context, adding and subtracting don’t seem to conceptually map to two separate resource collections. Instead of separating them based on the idea of “getting” different resources from each, we might want to group them based on the attributes of their function (i.e., take two numbers, do something to them, return the result).

With Suffixed Responders, we can do just that, rewriting the example above in a more procedural style:

class Calculator():
    def on_get_add(self, req, resp):
        resp.text = str(req.get_param_as_int('x') + req.get_param_as_int('y'))
        resp.status = falcon.HTTP_200

    def on_get_subtract(self, req, resp):
        resp.text = str(req.get_param_as_int('x') - req.get_param_as_int('y'))
        resp.status = falcon.HTTP_200


calc = Calculator()
app = falcon.App()
app.add_route('/add', calc, suffix='add')
app.add_route('/subtract', calc, suffix='subtract')

In the second iteration, using Suffixed Responders, we’re able to group responders based on their actions rather than the data they represent. This gives us added flexibility to accomodate situations in which a purely RESTful approach simply doesn’t fit.

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.App 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.

The compilation process is delayed until the first use of the router (on the first routed request) to reduce the time it takes to start the application. This may noticeably delay the first response of the application when a large number of routes have been added. When adding the last route to the application a compile flag may be provided to force the router to compile immediately, thus avoiding any delay for the first response.

Note

When using a multi-threaded web server to host the application, it is possible that multiple requests may be routed at the same time upon startup. Therefore, the framework employs a lock to ensure that only a single compilation of the decision tree is performed.

See also CompiledRouter.add_route()

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

Add 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.

  • compile (bool) –

    Optional flag that can be used to compile the routing logic on this call. By default, CompiledRouter delays compilation until the first request is routed. This may introduce a noticeable amount of latency when handling the first request, especially when the application implements a large number of routes. Setting compile to True when the last route is added ensures that the first request will not be delayed in this case (defaults to False).

    Note

    Always setting this flag to True may slow down the addition of new routes when hundreds of them are added at once. It is advisable to only set this flag to True when adding the final route.

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 – The falcon.Request or falcon.asgi.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]

Map 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, asgi=False)[source]

Map 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.

  • asgi (bool) – True if using an ASGI app, False otherwise (default False).

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}

Warning

If the template contains a trailing slash character, it will be stripped.

Note that this is different from the default behavior of add_route() used with the default CompiledRouter.

The strip_url_path_trailing_slash request option is not considered by compile_uri_template().

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

Deprecated since version 3.1.

falcon.app_helpers.prepare_middleware(middleware, independent_middleware=False, asgi=False)[source]

Check middleware interfaces and prepare the methods for request handling.

Note

This method is only applicable to WSGI apps.

Parameters:

middleware (iterable) – An iterable of middleware objects.

Keyword Arguments:
  • independent_middleware (bool) – True if the request and response middleware methods should be treated independently (default False)

  • asgi (bool) – True if an ASGI app, False otherwise (default False)

Returns:

A tuple of prepared middleware method tuples

Return type:

tuple

falcon.app_helpers.prepare_middleware_ws(middleware)[source]

Check middleware interfaces and prepare WebSocket methods for request handling.

Note

This method is only applicable to ASGI apps.

Parameters:

middleware (iterable) – An iterable of middleware objects.

Returns:

A two-item (request_mw, resource_mw) tuple, where request_mw is an ordered list of process_request_ws() methods, and resource_mw is an ordered list of process_resource_ws() methods.

Return type:

tuple

Custom HTTP Methods

While not normally advised, some applications may need to support non-standard HTTP methods, in addition to the standard HTTP methods like GET and PUT. To support custom HTTP methods, use one of the following methods:

  • Ideally, if you don’t use hooks in your application, you can easily add the custom methods in your application setup by overriding the value of falcon.constants.COMBINED_METHODS. For example:

    import falcon.constants
    falcon.constants.COMBINED_METHODS += ['FOO', 'BAR']
    
  • Due to the nature of hooks, if you do use them, you’ll need to define the FALCON_CUSTOM_HTTP_METHODS environment variable as a comma-delimited list of custom methods. For example:

    $ export FALCON_CUSTOM_HTTP_METHODS=FOO,BAR
    

Once you have used the appropriate method, your custom methods should be active. You then can define request methods like any other HTTP method:

# Handle the custom FOO method
def on_foo(self, req, resp):
    pass