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', request_type=<class 'falcon.request.Request'>, response_type=<class 'falcon.response.Response'>, middleware=None, router=None, independent_middleware=True)
[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.
Keyword Arguments: | |
---|---|
|
req_options
A set of behavioral options related to incoming requests. (See also: RequestOptions
)
resp_options
A set of behavioral options related to outgoing responses. (See also: ResponseOptions
)
router_options
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)
add_error_handler(exception, handler=None)
[source]
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.
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.
Note
By default, the framework installs two handlers, one for HTTPError
and one for HTTPStatus
. These can be overridden by adding a custom error handler method for the exception type in question.
Parameters: |
|
---|
add_route(uri_template, resource, **kwargs)
[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.
If no route matches the request, control then passes to a default responder that simply raises an instance of HTTPNotFound
.
This method delegates to the configured router’s add_route()
method. To override the default behavior, pass a custom router object to the API
initializer.
(See also: Routing)
Parameters: |
|
---|---|
Keyword Arguments: | |
suffix (str) – Optional responder name suffix for this route. If a suffix is provided, Falcon will map GET requests to |
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='/')
[source]
Register 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: |
|
---|
add_static_route(prefix, directory, downloadable=False, fallback_filename=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.
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:
api.add_static_route('/foo', foo_path) api.add_static_route('/foo/bar', foobar_path)
Parameters: |
|
---|
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.
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
The default serializer will not render any response body for HTTPError
instances where the has_representation
property evaluates to False
(such as in the case of types that subclass falcon.http_error.NoRepresentation
). However a custom serializer will be called regardless of the property value, and it may choose to override the representation logic.
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(('application/x-yaml', 'application/json')) if exception.has_representation and 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')
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 . |
---|
class falcon.RequestOptions
[source]
Defines a set of configurable request options.
An instance of this class is exposed via API.req_options
for configuring certain Request
behaviors.
keep_blank_qs_values
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.
Type: | bool |
---|
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 (default False
).
Enabling this option makes the form parameters accessible via params
, get_param()
, etc.
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 http://goo.gl/6rlcux).
auto_parse_qs_csv
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
becomes ['1', '2', '3', '4']
).
strip_url_path_trailing_slash
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.
default_media_type
The default media-type to use when deserializing a response. This value is normally set to the media type provided when a falcon.API
is initialized; however, if created independently, this will default to the DEFAULT_MEDIA_TYPE
specified by Falcon.
Type: | str |
---|
media_handlers
A dict-like object that allows you to configure the media-types that you would like to handle. By default, a handler is provided for the application/json
media type.
Type: | Handlers |
---|
class falcon.ResponseOptions
[source]
Defines a set of configurable response options.
An instance of this class is exposed via API.resp_options
for configuring certain Response
behaviors.
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 set_cookie()
’s secure
kwarg.
Type: | bool |
---|
default_media_type
The default Internet media type (RFC 2046) to use when deserializing a response. This value is normally set to the media type provided when a falcon.API
is initialized; however, if created independently, this will default to the DEFAULT_MEDIA_TYPE
specified by Falcon.
Type: | str |
---|
media_handlers
A dict-like object that allows you to configure the media-types that you would like to handle. By default, a handler is provided for the application/json
media type.
Type: | Handlers |
---|
static_media_types
A mapping of dot-prefixed file extensions to Internet media types (RFC 2046). Defaults to mimetypes.types_map
after calling mimetypes.init()
.
Type: | dict |
---|
class falcon.routing.CompiledRouterOptions
[source]
Defines a set of configurable router options.
An instance of this class is exposed via API.router_options
for configuring certain CompiledRouter
behaviors.
converters
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:
api.router_options.converters['mc'] = MyConverter
The identifier can then be used to employ the converter within a URI template:
api.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)
© 2019 by Falcon contributors
Licensed under the Apache License, Version 2.0.
https://falcon.readthedocs.io/en/2.0.0/api/api.html