Falcon’s API class is a WSGI “application” that you can host with any standard-compliant WSGI server.
import falcon app = falcon.API()
class falcon.API(media_type='application/json; charset=UTF-8', request_type=<class 'falcon.request.Request'>, response_type=<class 'falcon.response.Response'>, middleware=None, router=None, independent_middleware=False)
This class is the main entry point into a Falcon-based app.
Each API instance provides a callable WSGI interface and a routing engine.
A set of behavioral options related to incoming requests. See also:
A set of behavioral options related to outgoing responses. See also:
Registers a handler for a given exception error type.
Error handlers may be registered for any type, including
HTTPError. This feature provides a central location for logging and otherwise handling exceptions raised by responders, hooks, and middleware components.
Error handlers are matched in LIFO order. In other words, when searching for an error handler to match a raised exception, and more than one handler matches the exception type, the framework will choose the one that was most recently registered. Therefore, more general error handlers (e.g., for the standard
Exception type) should be added first, to avoid masking more specific handlers for subclassed types.
add_route(uri_template, resource, *args, **kwargs)
Associates a templatized URI path with a resource.
The following information describes the behavior of Falcon’s default router.
A resource is an instance of a class that 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
If your resource does not support a particular HTTP method, simply omit the corresponding responder and Falcon will reply with “405 Method not allowed” if that method is ever requested.
def on_post(self, req, resp): pass
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 is also provided for reading any data that was included in the body of the request.
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. This property could be used, for example, to provide a resource representation to a middleware component that would then serialize the representation according to the client’s preferred media type.
In addition to the standard
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:
A PUT request to “/user/kgriffs” would be routed to:
def on_put(self, req, resp, name): pass
Individual path segments may contain one or more field expressions, and fields need not span the entire path segment. For example:
Because field names correspond to argument names in responder methods, they must be valid Python identifiers.
Any additional args and kwargs not defined above are passed through to the underlying router’s
add_route() method. The default router does not expect any additional arguments, but custom routers may take advantage of this feature to receive additional options when setting up routes.
Registers a sink method for the API.
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.
Override the default serializer for instances of
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.
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.
HTTPError class contains helper methods, such as
to_dict(), that can be used from within custom serializers. For example:
def my_serializer(req, resp, exception): representation = None preferred = req.client_prefers(('application/x-yaml', 'application/json')) if preferred is not None: if preferred == 'application/json': representation = exception.to_json() else: representation = yaml.dump(exception.to_dict(), encoding=None) resp.body = representation resp.content_type = preferred resp.append_header('Vary', 'Accept')
serializer (callable) – A function taking the form |
Defines a set of configurable request options.
bool – Set to
True to keep query string fields even if they do not have a value (default
False). For comma-separated values, this option also determines whether or not empty elements in the parsed list are retained.
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
When this option is enabled, the request’s body stream will be left at EOF. The original data is not retained by the framework.
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 http://goo.gl/6rlcux).
False to treat commas in a query string value as literal characters, rather than as a comma- separated list (default
True). When this option is enabled, the value will be split on any non-percent-encoded commas. Disable this option when encoding lists as multiple occurrences of the same parameter, and when values may be encoded in alternative formats in which the comma character is significant.
False in order to retain a trailing slash, if present, at the end of the URL path (default
True). 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.
Defines a set of configurable response options.
bool – Set to
False in development environments to make the
secure attribute for all cookies default to
False. This can make testing easier by not requiring HTTPS. Note, however, that this setting can be overridden via
© 2012–2016 by Rackspace Hosting, Inc. and other contributors
Licensed under the Apache License, Version 2.0.