API Class¶
Falcon’s API class is a WSGI “application” that you can host with any standard-compliant WSGI server.
import falcon
api = application = 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)[source]¶ This class is the main entry point into a Falcon-based app.
Each API instance provides a callable WSGI interface and a routing engine.
Parameters: - media_type (str, optional) – Default media type to use as the value for the Content-Type header on responses (default ‘application/json’).
- middleware (object or list, optional) –
One or more objects (instantiated classes) that implement the following middleware component interface:
class ExampleComponent(object): def process_request(self, req, resp): """Process the request before routing it. 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, resp, resource, params): """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, resp, resource) """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. """
See also Middleware.
- request_type (Request, optional) –
Request
-like class to use instead of Falcon’s default class. Among other things, this feature affords inheriting fromfalcon.request.Request
in order to override thecontext_type
class variable. (defaultfalcon.request.Request
) - response_type (Response, optional) –
Response
-like class to use instead of Falcon’s default class. (defaultfalcon.response.Response
) - router (object, optional) – An instance of a custom router to use in lieu of the default engine. See also: Routing.
-
req_options
¶ RequestOptions – A set of behavioral options related to incoming requests.
-
add_error_handler
(exception, handler=None)[source]¶ Registers a handler for a given exception error type.
Parameters: - exception (type) – Whenever an error occurs when handling a request that is an instance of this exception class, the associated handler will be called.
- handler (callable) –
A function or callable object taking the form
func(ex, req, resp, 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(ex, req, resp, params): # TODO: Log the error # Convert to an instance of falcon.HTTPError raise falcon.HTTPError(falcon.HTTP_792)
Note
A handler can either raise an instance of
HTTPError
or modify resp manually in order to communicate information about the issue to the client.
-
add_route
(uri_template, resource, *args, **kwargs)[source]¶ Associates a templatized URI path with a resource.
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 on_get, on_post, on_put, etc.
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.
Responders must always define at least two arguments to receive request and response objects, respectively. For example:
def on_post(self, req, resp): pass
In addition, 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
Individual path segments may contain one or more field expressions. For example:
/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}
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).
- 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
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.
-
add_sink
(sink, prefix='/')[source]¶ 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.
Parameters: - sink (callable) – A callable taking the form
func(req, resp)
. - 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).
- sink (callable) – A callable taking the form
-
set_error_serializer
(serializer)[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.
The
falcon.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(('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
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. If this is not desirable, a custom error serializer may be used to override this behavior.
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
.
-
class
falcon.
RequestOptions
[source]¶ This class is a container for
Request
options.-
keep_blank_qs_values
¶ bool – Set to
True
in order to retain blank values in query string parameters (defaultFalse
).
-
auto_parse_form_urlencoded
¶ 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 (defaultFalse
). In this case, the request’s content stream will be left at EOF.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 http://goo.gl/6rlcux).
-