- class falcon.API(*args, **kwargs)[source]¶
This class is a compatibility alias of
falcon.App
.API
was renamed toApp
in Falcon 3.0 in order to reflect the breadth of applications thatApp
, and its ASGI counterpart in particular, can now be used for.This compatibility alias should be considered deprecated; it will be removed in a future release.
- add_error_handler(exception, handler=None)¶
Register a handler for one or more exception types.
Error handlers may be registered for any exception type, including
HTTPError
orHTTPStatus
. 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
orHTTPStatus
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 bycustom_handle_http_error()
.falcon.HTTPError
is a superclass offalcon.HTTPForbidden
and a subclass ofException
, so it is the most specific exception type with a registered handler.If an instance of
falcon.HTTPNotFound
is raised, it will be handled bycustom_handle_404()
, not bycustom_handle_not_found()
, becausecustom_handle_404()
was registered more recently.Note
By default, the framework installs three handlers, one for
HTTPError
, one forHTTPStatus
, and one for the standardException
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
, whereexception
is the error type specified above, andhandle
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)¶
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, resource, **kwargs)¶
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 theApp
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 toon_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 toon_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. SeeCompiledRouter.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, prefix='/')¶
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.
- 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, directory, downloadable=False, fallback_filename=None)¶
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 accomodate 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.
- set_error_serializer(serializer)¶
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 overriden. Seeadd_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, resp, exception): 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 offalcon.HTTPError
.