The App Class#

Falcon supports both the WSGI (falcon.App) and ASGI (falcon.asgi.App) protocols. This is done by instantiating the respective App class to create a callable WSGI or ASGI “application”.

Because Falcon’s App classes are built on WSGI and ASGI, you can host them with any standard-compliant server.

import falcon
import falcon.asgi

wsgi_app = falcon.App()
asgi_app = falcon.asgi.App()

WSGI App#

class falcon.App(media_type: str = 'application/json', request_type: Type[Request] | None = None, response_type: Type[Response] | None = None, middleware: object | Iterable[object] | None = None, router: CompiledRouter | None = None, independent_middleware: bool = True, cors_enable: bool = False, sink_before_static_route: bool = True)[source]#

The main entry point into a Falcon-based WSGI app.

Each App instance provides a callable WSGI interface and a routing engine (for ASGI applications, see falcon.asgi.App).

Note

The API class was renamed to App in Falcon 3.0. The old class name remains available as an alias for backwards-compatibility, but will be removed in a future release.

Keyword Arguments:
  • media_type (str) – Default media type to use when initializing RequestOptions and ResponseOptions. The falcon module provides a number of constants for common media types, such as falcon.MEDIA_MSGPACK, falcon.MEDIA_YAML, falcon.MEDIA_XML, etc.

  • middleware

    Either a single middleware component object or an iterable of objects (instantiated classes) that implement the following middleware component interface. Note that it is only necessary to implement the methods for the events you would like to handle; Falcon simply skips over any missing middleware methods:

    class ExampleMiddleware:
        def process_request(self, req: Request, resp: Response) -> None:
            """Process the request before routing it.
    
            Note:
                Because Falcon routes each request based on
                req.path, a request can be effectively re-routed
                by setting that attribute to a new value from
                within process_request().
    
            Args:
                req: Request object that will eventually be
                    routed to an on_* responder method.
                resp: Response object that will be routed to
                    the on_* responder.
            """
    
            def process_resource(
                self,
                req: Request,
                resp: Response,
                resource: object,
                params: dict[str, Any],
            ) -> None:
            """Process the request and resource *after* routing.
    
            Note:
                This method is only called when the request matches
                a route to a resource.
    
            Args:
                req: Request object that will be passed to the
                    routed responder.
                resp: Response object that will be passed to the
                    responder.
                resource: Resource object to which the request was
                    routed. May be None if no route was found for
                    the request.
                params: A dict-like object representing any
                    additional params derived from the route's URI
                    template fields, that will be passed to the
                    resource's responder method as keyword
                    arguments.
            """
    
        def process_response(
            self,
            req: Request,
            resp: Response,
            resource: object,
            req_succeeded: bool
        ) -> None:
            """Post-processing of the response (after routing).
    
            Args:
                req: Request object.
                resp: Response object.
                resource: Resource object to which the request was
                    routed. May be None if no route was found
                    for the request.
                req_succeeded: True if no exceptions were raised
                    while the framework processed and routed the
                    request; otherwise False.
            """
    

    (See also: Middleware)

  • request_typeRequest-like class to use instead of Falcon’s default class. Among other things, this feature affords inheriting from falcon.Request in order to override the context_type class variable (default: falcon.Request)

  • response_typeResponse-like class to use instead of Falcon’s default class (default: falcon.Response)

  • router (object) – An instance of a custom router to use in lieu of the default engine. (See also: Custom Routers)

  • independent_middleware (bool) – Set to False if response middleware should not be executed independently of whether or not request middleware raises an exception (default True). When this option is set to False, a middleware component’s process_response() method will NOT be called when that same component’s process_request() (or that of a component higher up in the stack) raises an exception.

  • cors_enable (bool) – Set this flag to True to enable a simple CORS policy for all responses, including support for preflighted requests. An instance of CORSMiddleware can instead be passed to the middleware argument to customize its behaviour. (default False). (See also: CORS)

  • sink_before_static_route (bool) – Indicates if the sinks should be processed before (when True) or after (when False) the static routes. This has an effect only if no route was matched. (default True)

add_error_handler(exception: Type[_BE], handler: Callable[[Request, Response, _BE, Dict[str, Any]], None]) None[source]#
add_error_handler(exception: Type[BaseException] | Iterable[Type[BaseException]], handler: Callable[[Request, Response, BaseException, Dict[str, Any]], None] | None = None) None

Register a handler for one or more exception types.

Error handlers may be registered for any exception type, including HTTPError or HTTPStatus. This feature provides a central location for logging and otherwise handling exceptions raised by responders, hooks, and middleware components.

A handler can raise an instance of HTTPError or HTTPStatus to communicate information about the issue to the client. Alternatively, a handler may modify resp directly.

An error handler “matches” a raised exception if the exception is an instance of the corresponding exception type. If more than one error handler matches the raised exception, the framework will choose the most specific one, as determined by the method resolution order of the raised exception type. If multiple error handlers are registered for the same exception class, then the most recently-registered handler is used.

For example, suppose we register error handlers as follows:

app = App()
app.add_error_handler(falcon.HTTPNotFound, custom_handle_not_found)
app.add_error_handler(falcon.HTTPError, custom_handle_http_error)
app.add_error_handler(Exception, custom_handle_uncaught_exception)
app.add_error_handler(falcon.HTTPNotFound, custom_handle_404)

If an instance of falcon.HTTPForbidden is raised, it will be handled by custom_handle_http_error(). falcon.HTTPError is a superclass of falcon.HTTPForbidden and a subclass of Exception, so it is the most specific exception type with a registered handler.

If an instance of falcon.HTTPNotFound is raised, it will be handled by custom_handle_404(), not by custom_handle_not_found(), because custom_handle_404() was registered more recently.

Note

By default, the framework installs three handlers, one for HTTPError, one for HTTPStatus, and one for the standard Exception type, which prevents passing uncaught exceptions to the WSGI server. These can be overridden by adding a custom error handler method for the exception type in question.

Parameters:
  • exception (type or iterable of types) – When handling a request, whenever an error occurs that is an instance of the specified type(s), the associated handler will be called. Either a single type or an iterable of types may be specified.

  • handler (callable) –

    A function or callable object taking the form func(req, resp, ex, params).

    If not specified explicitly, the handler will default to exception.handle, where exception is the error type specified above, and handle is a static method (i.e., decorated with @staticmethod) that accepts the same params just described. For example:

    class CustomException(CustomBaseException):
    
        @staticmethod
        def handle(req, resp, ex, params):
            # TODO: Log the error
            # Convert to an instance of falcon.HTTPError
            raise falcon.HTTPError(falcon.HTTP_792)
    

    If an iterable of exception types is specified instead of a single type, the handler must be explicitly specified.

Changed in version 3.0: The error handler is now selected by the most-specific matching error class, rather than the most-recently registered matching error class.

add_middleware(middleware: object | Iterable[object]) None[source]#

Add one or more additional middleware components.

Parameters:

middleware – Either a single middleware component or an iterable of components to add. The component(s) will be invoked, in order, as if they had been appended to the original middleware list passed to the class initializer.

add_route(uri_template: str, resource: object, **kwargs: Any) None[source]#

Associate a templatized URI path with a resource.

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.

Note

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, but 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 method delegates to the configured router’s add_route() method. To override the default behavior, pass a custom router object to the App initializer.

(See also: Routing)

Parameters:
  • uri_template (str) –

    A templatized URI. Care must be taken to ensure the template does not mask any sink patterns, if any are registered.

    (See also: add_sink())

    Warning

    If strip_url_path_trailing_slash is enabled, uri_template should be provided without a trailing slash.

    (See also: How does Falcon handle a trailing slash in the request path?)

  • resource (instance) –

    Object which represents a REST resource. Falcon will pass GET requests to on_get(), PUT requests to on_put(), 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.

    Note

    When using an async version of the App, all request handlers must be awaitable coroutine functions.

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. For example:

    class Baz(object):
    
        def on_get_foo(self, req, resp):
            pass
    
        def on_get_bar(self, req, resp):
            pass
    
    baz = Baz()
    app = falcon.App()
    app.add_route('/foo', baz, suffix='foo')
    app.add_route('/bar', baz, suffix='bar')
    

  • compile (bool) – Optional flag that can be provided when using the default CompiledRouter to compile the routing logic on this call, since it will otherwise delay compilation until the first request is routed. See CompiledRouter.add_route() for further details.

Note

Any additional keyword arguments not defined above are passed through to the underlying router’s add_route() method. The default router ignores any additional keyword arguments, but custom routers may take advantage of this feature to receive additional options when setting up routes. Custom routers MUST accept such arguments using the variadic pattern (**kwargs), and ignore any keyword arguments that they don’t support.

add_sink(sink: SinkCallable, prefix: str | Pattern[str] = '/') None[source]#

Register a sink method for the App.

If no route matches a request, but the path in the requested URI matches a sink prefix, Falcon will pass control to the associated sink, regardless of the HTTP method requested.

Using sinks, you can drain and dynamically handle a large number of routes, when creating static resources and responders would be impractical. For example, you might use a sink to create a smart proxy that forwards requests to one or more backend services.

Note

To support CORS preflight requests when using the default CORS middleware, either by setting App.cors_enable=True or by adding the CORSMiddleware to the App.middleware, the sink should set the Allow header in the request to the allowed method values when serving an OPTIONS request. If the Allow header is missing from the response, the default CORS middleware will deny the preflight request.

Parameters:
  • sink (callable) –

    A callable taking the form func(req, resp, **kwargs).

    Note

    When using an async version of the App, this must be a coroutine.

  • prefix (str) –

    A regex string, typically starting with ‘/’, which will trigger the sink if it matches the path portion of the request’s URI. Both strings and precompiled regex objects may be specified. Characters are matched starting at the beginning of the URI path.

    Note

    Named groups are converted to kwargs and passed to the sink as such.

    Warning

    If the prefix overlaps a registered route template, the route will take precedence and mask the sink.

    (See also: add_route())

add_static_route(prefix: str, directory: str | Path, downloadable: bool = False, fallback_filename: str | None = None) None[source]#

Add a route to a directory of static files.

Static routes provide a way to serve files directly. This feature provides an alternative to serving files at the web server level when you don’t have that option, when authorization is required, or for testing purposes.

Warning

Serving files directly from the web server, rather than through the Python app, will always be more efficient, and therefore should be preferred in production deployments. For security reasons, the directory and the fallback_filename (if provided) should be read only for the account running the application.

Warning

If you need to serve large files and/or progressive downloads (such as in the case of video streaming) through the Falcon app, check that your application server’s timeout settings can accommodate the expected request duration (for instance, the popular Gunicorn kills sync workers after 30 seconds unless configured otherwise).

Note

For ASGI apps, file reads are made non-blocking by scheduling them on the default executor.

Static routes are matched in LIFO order. Therefore, if the same prefix is used for two routes, the second one will override the first. This also means that more specific routes should be added after less specific ones. For example, the following sequence would result in '/foo/bar/thing.js' being mapped to the '/foo/bar' route, and '/foo/xyz/thing.js' being mapped to the '/foo' route:

app.add_static_route('/foo', foo_path)
app.add_static_route('/foo/bar', foobar_path)
Parameters:
  • prefix (str) –

    The path prefix to match for this route. If the path in the requested URI starts with this string, the remainder of the path will be appended to the source directory to determine the file to serve. This is done in a secure manner to prevent an attacker from requesting a file outside the specified directory.

    Note that static routes are matched in LIFO order, and are only attempted after checking dynamic routes and sinks.

  • directory (Union[str, pathlib.Path]) – The source directory from which to serve files.

  • downloadable (bool) – Set to True to include a Content-Disposition header in the response. The “filename” directive is simply set to the name of the requested file.

  • fallback_filename (str) – Fallback filename used when the requested file is not found. Can be a relative path inside the prefix folder or any valid absolute path.

req_options: RequestOptions#

A set of behavioral options related to incoming requests.

See also: RequestOptions

resp_options: ResponseOptions#

A set of behavioral options related to outgoing responses.

See also: ResponseOptions

property router_options: CompiledRouterOptions#

Configuration options for the router.

If a custom router is in use, and it does not expose any configurable options, referencing this attribute will raise an instance of AttributeError.

See also: CompiledRouterOptions.

set_error_serializer(serializer: Callable[[Request, Response, HTTPError], None]) None[source]#

Override the default serializer for instances of HTTPError.

When a responder raises an instance of HTTPError, Falcon converts it to an HTTP response automatically. The default serializer supports JSON and XML, but may be overridden by this method to use a custom serializer in order to support other media types.

Note

If a custom media type is used and the type includes a “+json” or “+xml” suffix, the default serializer will convert the error to JSON or XML, respectively.

Note

A custom serializer set with this method may not be called if the default error handler for HTTPError has been overridden. See add_error_handler() for more details.

The HTTPError class contains helper methods, such as to_json() and to_dict(), that can be used from within custom serializers. For example:

def my_serializer(
    req: Request, resp: Response, exception: HTTPError
) -> None:
    representation = None

    preferred = req.client_prefers((falcon.MEDIA_YAML, falcon.MEDIA_JSON))

    if preferred is not None:
        if preferred == falcon.MEDIA_JSON:
            resp.data = exception.to_json()
        else:
            resp.text = yaml.dump(exception.to_dict(), encoding=None)
        resp.content_type = preferred

    resp.append_header('Vary', 'Accept')
Parameters:

serializer (callable) – A function taking the form func(req, resp, exception), where req is the request object that was passed to the responder method, resp is the response object, and exception is an instance of falcon.HTTPError.

ASGI App#

class falcon.asgi.App(media_type: str = 'application/json', request_type: Type[Request] | None = None, response_type: Type[Response] | None = None, middleware: object | Iterable[object] | None = None, router: CompiledRouter | None = None, independent_middleware: bool = True, cors_enable: bool = False, sink_before_static_route: bool = True)[source]#

The main entry point into a Falcon-based ASGI app.

Each App instance provides a callable ASGI interface and a routing engine (for WSGI applications, see falcon.App).

Keyword Arguments:
  • media_type (str) – Default media type to use when initializing RequestOptions and ResponseOptions. The falcon module provides a number of constants for common media types, such as falcon.MEDIA_MSGPACK, falcon.MEDIA_YAML, falcon.MEDIA_XML, etc.

  • middleware

    Either a single middleware component object or an iterable of objects (instantiated classes) that implement the middleware component interface shown below.

    The interface provides support for handling both ASGI worker lifespan events and per-request events. However, because lifespan events are an optional part of the ASGI specification, they may or may not fire depending on your ASGI server.

    A lifespan event handler can be used to perform startup or shutdown activities for the main event loop. An example of this would be creating a connection pool and subsequently closing the connection pool to release the connections.

    Note

    In a multi-process environment, lifespan events will be triggered independently for the individual event loop associated with each process.

    Note

    The framework requires that all middleware methods be implemented as coroutine functions via async def. However, it is possible to implement middleware classes that support both ASGI and WSGI apps by distinguishing the ASGI methods with an *_async postfix (see also: Middleware).

    It is only necessary to implement the methods for the events you would like to handle; Falcon simply skips over any missing middleware methods:

    class ExampleMiddleware:
        async def process_startup(
            self, scope: dict[str, Any], event: dict[str, Any]
        ) -> None:
            """Process the ASGI lifespan startup event.
    
            Invoked when the server is ready to start up and
            receive connections, but before it has started to
            do so.
    
            To halt startup processing and signal to the server that it
            should terminate, simply raise an exception and the
            framework will convert it to a "lifespan.startup.failed"
            event for the server.
    
            Args:
                scope (dict): The ASGI scope dictionary for the
                    lifespan protocol. The lifespan scope exists
                    for the duration of the event loop.
                event (dict): The ASGI event dictionary for the
                    startup event.
            """
    
        async def process_shutdown(
            self, scope: dict[str, Any], event: dict[str, Any]
        ) -> None:
            """Process the ASGI lifespan shutdown event.
    
            Invoked when the server has stopped accepting
            connections and closed all active connections.
    
            To halt shutdown processing and signal to the server
            that it should immediately terminate, simply raise an
            exception and the framework will convert it to a
            "lifespan.shutdown.failed" event for the server.
    
            Args:
                scope (dict): The ASGI scope dictionary for the
                    lifespan protocol. The lifespan scope exists
                    for the duration of the event loop.
                event (dict): The ASGI event dictionary for the
                    shutdown event.
            """
    
        async def process_request(
            self, req: Request, resp: Response
        ) -> None:
            """Process the request before routing it.
    
            Note:
                Because Falcon routes each request based on
                req.path, a request can be effectively re-routed
                by setting that attribute to a new value from
                within process_request().
    
            Args:
                req: Request object that will eventually be
                    routed to an on_* responder method.
                resp: Response object that will be routed to
                    the on_* responder.
            """
    
        async def process_resource(
            self,
            req: Request,
            resp: Response,
            resource: object,
            params: dict[str, Any],
        ) -> None:
            """Process the request and resource *after* routing.
    
            Note:
                This method is only called when the request matches
                a route to a resource.
    
            Args:
                req: Request object that will be passed to the
                    routed responder.
                resp: Response object that will be passed to the
                    responder.
                resource: Resource object to which the request was
                    routed. May be ``None`` if no route was found for
                    the request.
                params: A dict-like object representing any
                    additional params derived from the route's URI
                    template fields, that will be passed to the
                    resource's responder method as keyword
                    arguments.
            """
    
        async def process_response(
            self,
            req: Request,
            resp: Response,
            resource: object,
            req_succeeded: bool
        ) -> None:
            """Post-processing of the response (after routing).
    
            Args:
                req: Request object.
                resp: Response object.
                resource: Resource object to which the request was
                    routed. May be ``None`` if no route was found
                    for the request.
                req_succeeded: True if no exceptions were raised
                    while the framework processed and routed the
                    request; otherwise False.
            """
    
        # WebSocket methods
        async def process_request_ws(
            self, req: Request, ws: WebSocket
        ) -> None:
            """Process a WebSocket handshake request before routing it.
    
            Note:
                Because Falcon routes each request based on req.path, a
                request can be effectively re-routed by setting that
                attribute to a new value from within process_request().
    
            Args:
                req: Request object that will eventually be
                    passed into an on_websocket() responder method.
                ws: The WebSocket object that will be passed into
                    on_websocket() after routing.
            """
    
        async def process_resource_ws(
            self,
            req: Request,
            ws: WebSocket,
            resource: object,
            params: dict[str, Any],
        ) -> None:
            """Process a WebSocket handshake request after routing.
    
            Note:
                This method is only called when the request matches
                a route to a resource.
    
            Args:
                req: Request object that will be passed to the
                    routed responder.
                ws: WebSocket object that will be passed to the
                    routed responder.
                resource: Resource object to which the request was
                    routed.
                params: A dict-like object representing any additional
                    params derived from the route's URI template fields,
                    that will be passed to the resource's responder
                    method as keyword arguments.
            """
    

    (See also: Middleware)

  • request_typeRequest-like class to use instead of Falcon’s default class. Among other things, this feature affords inheriting from falcon.asgi.Request in order to override the context_type class variable (default: falcon.asgi.Request)

  • response_typeResponse-like class to use instead of Falcon’s default class (default: falcon.asgi.Response)

  • router (object) – An instance of a custom router to use in lieu of the default engine. (See also: Custom Routers)

  • independent_middleware (bool) – Set to False if response middleware should not be executed independently of whether or not request middleware raises an exception (default True). When this option is set to False, a middleware component’s process_response() method will NOT be called when that same component’s process_request() (or that of a component higher up in the stack) raises an exception.

  • cors_enable (bool) – Set this flag to True to enable a simple CORS policy for all responses, including support for preflighted requests. An instance of CORSMiddleware can instead be passed to the middleware argument to customize its behaviour. (default False). (See also: CORS)

  • sink_before_static_route (bool) – Indicates if the sinks should be processed before (when True) or after (when False) the static routes. This has an effect only if no route was matched. (default True)

add_error_handler(exception: Type[_BE], handler: Callable[[Request, Response, _BE, Dict[str, Any]], Awaitable[None]]) None[source]#
add_error_handler(exception: Type[BaseException] | Iterable[Type[BaseException]], handler: AsgiErrorHandler | None = None) None

Register a handler for one or more exception types.

Error handlers may be registered for any exception type, including HTTPError or HTTPStatus. This feature provides a central location for logging and otherwise handling exceptions raised by responders, hooks, and middleware components.

A handler can raise an instance of HTTPError or HTTPStatus to communicate information about the issue to the client. Alternatively, a handler may modify resp directly.

An error handler “matches” a raised exception if the exception is an instance of the corresponding exception type. If more than one error handler matches the raised exception, the framework will choose the most specific one, as determined by the method resolution order of the raised exception type. If multiple error handlers are registered for the same exception class, then the most recently-registered handler is used.

For example, suppose we register error handlers as follows:

app = App()
app.add_error_handler(falcon.HTTPNotFound, custom_handle_not_found)
app.add_error_handler(falcon.HTTPError, custom_handle_http_error)
app.add_error_handler(Exception, custom_handle_uncaught_exception)
app.add_error_handler(falcon.HTTPNotFound, custom_handle_404)

If an instance of falcon.HTTPForbidden is raised, it will be handled by custom_handle_http_error(). falcon.HTTPError is a superclass of falcon.HTTPForbidden and a subclass of Exception, so it is the most specific exception type with a registered handler.

If an instance of falcon.HTTPNotFound is raised, it will be handled by custom_handle_404(), not by custom_handle_not_found(), because custom_handle_404() was registered more recently.

Note

By default, the framework installs three handlers, one for HTTPError, one for HTTPStatus, and one for the standard Exception type, which prevents passing uncaught exceptions to the WSGI server. These can be overridden by adding a custom error handler method for the exception type in question.

When a generic unhandled exception is raised while handling a WebSocket connection, the default handler will close the connection with the standard close code 1011 (Internal Error). If your ASGI server does not support this code, the framework will use code 3011 instead; or you can customize it via the error_close_code property of ws_options.

On the other hand, if an on_websocket() responder raises an instance of HTTPError, the default error handler will close the WebSocket connection with a framework close code derived by adding 3000 to the HTTP status code (e.g., 3404)

Parameters:
  • exception (type or iterable of types) – When handling a request, whenever an error occurs that is an instance of the specified type(s), the associated handler will be called. Either a single type or an iterable of types may be specified.

  • handler (callable) –

    A coroutine function taking the form:

    async def func(req, resp, ex, params, ws=None):
        pass
    

    In the case of a WebSocket connection, the resp argument will be None, while the ws keyword argument will receive the WebSocket object representing the connection.

    If the handler keyword argument is not provided to add_error_handler(), the handler will default to exception.handle, where exception is the error type specified above, and handle is a static method (i.e., decorated with @staticmethod) that accepts the params just described. For example:

    class CustomException(CustomBaseException):
    
        @staticmethod
        async def handle(req, resp, ex, params):
            # TODO: Log the error
            # Convert to an instance of falcon.HTTPError
            raise falcon.HTTPError(falcon.HTTP_792)
    

    Note, however, that if an iterable of exception types is specified instead of a single type, the handler must be explicitly specified using the handler keyword argument.

add_route(uri_template: str, resource: object, **kwargs: Any) None[source]#

Associate a templatized URI path with a resource.

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.

Note

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, but 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 method delegates to the configured router’s add_route() method. To override the default behavior, pass a custom router object to the App initializer.

(See also: Routing)

Parameters:
  • uri_template (str) –

    A templatized URI. Care must be taken to ensure the template does not mask any sink patterns, if any are registered.

    (See also: add_sink())

    Warning

    If strip_url_path_trailing_slash is enabled, uri_template should be provided without a trailing slash.

    (See also: How does Falcon handle a trailing slash in the request path?)

  • resource (instance) –

    Object which represents a REST resource. Falcon will pass GET requests to on_get(), PUT requests to on_put(), 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.

    Note

    When using an async version of the App, all request handlers must be awaitable coroutine functions.

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. For example:

    class Baz(object):
    
        def on_get_foo(self, req, resp):
            pass
    
        def on_get_bar(self, req, resp):
            pass
    
    baz = Baz()
    app = falcon.App()
    app.add_route('/foo', baz, suffix='foo')
    app.add_route('/bar', baz, suffix='bar')
    

  • compile (bool) – Optional flag that can be provided when using the default CompiledRouter to compile the routing logic on this call, since it will otherwise delay compilation until the first request is routed. See CompiledRouter.add_route() for further details.

Note

Any additional keyword arguments not defined above are passed through to the underlying router’s add_route() method. The default router ignores any additional keyword arguments, but custom routers may take advantage of this feature to receive additional options when setting up routes. Custom routers MUST accept such arguments using the variadic pattern (**kwargs), and ignore any keyword arguments that they don’t support.

add_sink(sink: AsgiSinkCallable, prefix: str | Pattern[str] = '/') None[source]#

Register a sink method for the App.

If no route matches a request, but the path in the requested URI matches a sink prefix, Falcon will pass control to the associated sink, regardless of the HTTP method requested.

Using sinks, you can drain and dynamically handle a large number of routes, when creating static resources and responders would be impractical. For example, you might use a sink to create a smart proxy that forwards requests to one or more backend services.

Note

To support CORS preflight requests when using the default CORS middleware, either by setting App.cors_enable=True or by adding the CORSMiddleware to the App.middleware, the sink should set the Allow header in the request to the allowed method values when serving an OPTIONS request. If the Allow header is missing from the response, the default CORS middleware will deny the preflight request.

Parameters:
  • sink (callable) –

    A callable taking the form func(req, resp, **kwargs).

    Note

    When using an async version of the App, this must be a coroutine.

  • prefix (str) –

    A regex string, typically starting with ‘/’, which will trigger the sink if it matches the path portion of the request’s URI. Both strings and precompiled regex objects may be specified. Characters are matched starting at the beginning of the URI path.

    Note

    Named groups are converted to kwargs and passed to the sink as such.

    Warning

    If the prefix overlaps a registered route template, the route will take precedence and mask the sink.

    (See also: add_route())

ws_options: WebSocketOptions#

A set of behavioral options related to WebSocket connections.

See also: WebSocketOptions.

Options#

class falcon.RequestOptions[source]#

Defines a set of configurable request options.

An instance of this class is exposed via falcon.App.req_options and falcon.asgi.App.req_options for configuring certain Request and falcon.asgi.Request behaviors, respectively.

property auto_parse_form_urlencoded: bool#

Set to True in order to automatically consume the request stream and merge the results into the request’s query string params when the request’s content type is application/x-www-form-urlencoded` (default False).

Enabling this option for WSGI apps makes the form parameters accessible via params, get_param(), etc.

Deprecated since version 3.0: The auto_parse_form_urlencoded option is not supported for ASGI apps, and is considered deprecated for WSGI apps as of Falcon 3.0, in favor of accessing URL-encoded forms through get_media().

The attribute and the auto-parsing functionality will be removed entirely in Falcon 5.0.

See also: How can I access POSTed form params?.

Warning

When this option is enabled, the request’s body stream will be left at EOF. The original data is not retained by the framework.

Note

The character encoding for fields, before percent-encoding non-ASCII bytes, is assumed to be UTF-8. The special _charset_ field is ignored if present.

Falcon expects form-encoded request bodies to be encoded according to the standard W3C algorithm (see also https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application%2Fx-www-form-urlencoded-encoding-algorithm).

auto_parse_qs_csv: bool#

Set to True to split query string values on any non-percent-encoded commas (default False).

When False, values containing commas are left as-is. In this mode, list items are taken only from multiples of the same parameter name within the query string (i.e. t=1,2,3&t=4 becomes ['1,2,3', '4']).

When auto_parse_qs_csv is set to True, the query string value is also split on non-percent-encoded commas and these items are added to the final list (i.e. t=1,2,3&t=4,5 becomes ['1', '2', '3', '4', '5']).

Warning

Enabling this option will cause the framework to misinterpret any JSON values that include literal (non-percent-encoded) commas. If the query string may include JSON, you can use JSON array syntax in lieu of CSV as a workaround.

default_media_type: str#

The default media-type used to deserialize a request body, when the Content-Type header is missing or ambiguous.

This value is normally set to the media type provided to the falcon.App or falcon.asgi.App initializer; however, if created independently, this will default to falcon.DEFAULT_MEDIA_TYPE.

keep_black_qs_values: bool#

Set to False to ignore query string params that have missing or blank values (default True).

For comma-separated values, this option also determines whether or not empty elements in the parsed list are retained.

media_handlers: Handlers#

A dict-like object for configuring the media-types to handle.

By default, handlers are provided for the application/json, application/x-www-form-urlencoded and multipart/form-data media types.

strip_url_path_trailing_slash: bool#

Set to True in order to strip the trailing slash, if present, at the end of the URL path (default False).

When this option is enabled, the URL path is normalized by stripping the trailing slash character. This lets the application define a single route to a resource for a path that may or may not end in a forward slash. However, this behavior can be problematic in certain cases, such as when working with authentication schemes that employ URL-based signatures.

class falcon.ResponseOptions[source]#

Defines a set of configurable response options.

An instance of this class is exposed via falcon.App.resp_options and falcon.asgi.App.resp_options for configuring certain Response behaviors.

default_media_type: str#

The default Internet media type (RFC 2046) to use when rendering a response, when the Content-Type header is not set explicitly.

This value is normally set to the media type provided when a falcon.App is initialized; however, if created independently, this will default to falcon.DEFAULT_MEDIA_TYPE.

media_handlers: Handlers#

A dict-like object for configuring the media-types to handle.

Default handlers are provided for the application/json, application/x-www-form-urlencoded and multipart/form-data media types.

secure_cookies_by_default: bool#

Set to False in development environments to make the secure attribute for all cookies. (default True).

This can make testing easier by not requiring HTTPS. Note, however, that this setting can be overridden via set_cookie()’s secure kwarg.

static_media_types: Dict[str, str]#

A mapping of dot-prefixed file extensions to Internet media types (RFC 2046).

Defaults to mimetypes.types_map after calling mimetypes.init().

xml_error_serialization: bool#

Set to False to disable automatic inclusion of the XML handler in the default error serializer (default True).

Enabling this option does not make Falcon automatically render all error responses in XML, but it is used only in the case the client prefers (via the Accept request header) XML to JSON and other configured media handlers.

Note

Falcon 5.0 will either change the default to False, or remove the automatic XML error serialization altogether.

Note

This option has no effect when a custom error serializer, set using set_error_serializer(), is in use.

Added in version 4.0.

class falcon.routing.CompiledRouterOptions[source]#

Defines a set of configurable router options.

An instance of this class is exposed via falcon.App.router_options and falcon.asgi.App.router_options for configuring certain CompiledRouter behaviors.

converters: ConverterDict#

Represents the collection of named converters that may be referenced in URI template field expressions.

Adding additional converters is simply a matter of mapping an identifier to a converter class:

app.router_options.converters['mc'] = MyConverter

The identifier can then be used to employ the converter within a URI template:

app.add_route('/{some_field:mc}', some_resource)

Converter names may only contain ASCII letters, digits, and underscores, and must start with either a letter or an underscore.

Warning

Converter instances are shared between requests. Therefore, in threaded deployments, care must be taken to implement custom converters in a thread-safe manner.

(See also: Field Converters)