API Reference¶
This part of the documentation covers most of the interfaces for Flask-Rebar.
Rebar Extension¶
-
class
flask_rebar.
Rebar
¶ The main entry point for the Flask-Rebar extension.
This registers handler registries with the Flask application and initializes all the Flask-Rebar goodies.
Example usage:
app = Flask(__name__) rebar = Rebar() registry = rebar.create_handler_registry() @registry.handles() def handler(): ... rebar.init_app(app)
-
create_handler_registry
(prefix=None, default_authenticators=None, default_headers_schema=None, default_mimetype=None, swagger_generator=None, spec_path='/swagger', swagger_ui_path='/swagger/ui')¶ Create a new handler registry and add to this extension’s set of registered registries.
When calling
Rebar.init_app()
, all registries created via this method will be registered with the Flask application.Parameters are the same for the
HandlerRegistry
constructor.Parameters: - prefix (str) – URL prefix for all handlers registered with this registry instance.
- Authenticator, None) default_authenticators (Union(List(Authenticator),) – List of Authenticators to use for all handlers as a default.
- default_headers_schema (marshmallow.Schema) – Schema to validate the headers on all requests as a default.
- default_mimetype (str) – Default response content-type if no content and not otherwise specified by the handler.
- swagger_generator (flask_rebar.swagger_generation.swagger_generator.SwaggerGeneratorI) – Object to generate a Swagger specification from this registry. This will be the Swagger generator that is used in the endpoints swagger and swagger UI that are added to the API. If left as None, a SwaggerV2Generator instance will be used.
- spec_path (str) – The OpenAPI specification as a JSON document will be hosted at this URL. If set as None, no swagger specification will be hosted.
- swagger_ui_path (str) – The HTML Swagger UI will be hosted at this URL. If set as None, no Swagger UI will be hosted.
Return type:
-
add_handler_registry
(registry)¶ Register a handler registry with the extension.
There is no need to call this if a handler registry was created via
Rebar.create_handler_registry()
.Parameters: registry (HandlerRegistry) –
-
validated_body
¶ Proxy to the result of validating/transforming an incoming request body with the request_body_schema a handler was registered with.
Return type: dict
-
validated_args
¶ Proxy to the result of validating/transforming an incoming request’s query string with the query_string_schema a handler was registered with.
Return type: dict
-
validated_headers
¶ Proxy to the result of validating/transforming an incoming request’s headers with the headers_schema a handler was registered with.
Return type: dict
-
add_uncaught_exception_handler
(func)¶ Add a function that will be called for uncaught exceptions, i.e. exceptions that will result in a 500 error.
This function should accept the exception instance as a single positional argument.
All handlers will be called in the order they are added.
Parameters: func (Callable) –
-
init_app
(app)¶ Register all the handler registries with a Flask application.
Parameters: app (flask.Flask) –
-
Handler Registry¶
-
class
flask_rebar.
HandlerRegistry
(prefix=None, default_authenticators=None, default_headers_schema=None, default_mimetype=None, swagger_generator=None, spec_path='/swagger', spec_ui_path='/swagger/ui')¶ Registry for request handlers.
This should typically be instantiated via a
Rebar
instance:rebar = Rebar() registry = rebar.create_handler_registry()
Although it can be instantiated independently and added to the registry:
rebar = Rebar() registry = HandlerRegistry() rebar.add_handler_registry(registry)
Parameters: prefix (str) – URL prefix for all handlers registered with this registry instance. - :param Union(flask_rebar.authenticators.Authenticator, List(flask_rebar.authenticators.Authenticator), None)
- default_authenticators: List of Authenticators to use for all handlers as a default.
Parameters: - default_headers_schema (marshmallow.Schema) – Schema to validate the headers on all requests as a default.
- default_mimetype (str) – Default response content-type if no content and not otherwise specified by the handler.
- swagger_generator (flask_rebar.swagger_generation.swagger_generator.SwaggerGeneratorI) – Object to generate a Swagger specification from this registry. This will be the Swagger generator that is used in the endpoints swagger and swagger UI that are added to the API. If left as None, a SwaggerV2Generator instance will be used.
- spec_path (str) – The Swagger specification as a JSON document will be hosted at this URL. If set as None, no swagger specification will be hosted.
- spec_ui_path (str) – The HTML Swagger UI will be hosted at this URL. If set as None, no Swagger UI will be hosted.
-
set_default_authenticator
(authenticator)¶ Sets a handler authenticator to be used by default.
Parameters: flask_rebar.authenticators.Authenticator) authenticator (Union(None,) –
-
set_default_authenticators
(authenticators)¶ Sets the handler authenticators to be used by default.
Parameters: authenticators (Union(List(flask_rebar.authenticators.Authenticator))) –
-
set_default_headers_schema
(headers_schema)¶ Sets the schema to be used by default to validate incoming headers.
Parameters: headers_schema (marshmallow.Schema) –
-
clone
()¶ Returns a new, shallow-copied instance of
HandlerRegistry
.Return type: HandlerRegistry
-
add_handler
(func, rule, method='GET', endpoint=None, response_body_schema=None, query_string_schema=None, request_body_schema=None, headers_schema=<class 'flask_rebar.utils.defaults.USE_DEFAULT'>, authenticators=<class 'flask_rebar.utils.defaults.USE_DEFAULT'>, tags=None, mimetype=<class 'flask_rebar.utils.defaults.USE_DEFAULT'>, hidden=False)¶ Registers a function as a request handler.
Parameters: - func – The Flask “view_func”
- rule (str) – The Flask “rule”
- method (str) – The HTTP method this handler accepts
- endpoint (str) –
- marshmallow.Schema] response_body_schema (dict[int,) – Dictionary mapping response codes to schemas to use to marshal the response. For now this assumes everything is JSON.
- query_string_schema (marshmallow.Schema) – Schema to use to deserialize query string arguments.
- request_body_schema (marshmallow.Schema) – Schema to use to deserialize the request body. For now this assumes everything is JSON.
- headers_schema (Type[USE_DEFAULT]|None|marshmallow.Schema) – Schema to use to grab and validate headers.
- authenticators (Type[USE_DEFAULT]|None|List(Authenticator)|Authenticator) – A list of authenticator objects to authenticate incoming requests. If left as USE_DEFAULT, the Rebar’s default will be used. Set to None to make this an unauthenticated handler.
- tags (Sequence[str]) – Arbitrary strings to tag the handler with. These will translate to Swagger operation tags.
- mimetype (Type[USE_DEFAULT]|None|str) – Content-Type header to add to the response schema
- hidden (bool) – if hidden, documentation is not created for this request handler by default
-
handles
(rule, method='GET', endpoint=None, response_body_schema=None, query_string_schema=None, request_body_schema=None, headers_schema=<class 'flask_rebar.utils.defaults.USE_DEFAULT'>, authenticators=<class 'flask_rebar.utils.defaults.USE_DEFAULT'>, tags=None, mimetype=<class 'flask_rebar.utils.defaults.USE_DEFAULT'>, hidden=False)¶ Same arguments as
HandlerRegistry.add_handler()
, except this can be used as a decorator.
Authenticator Objects¶
-
class
flask_rebar.authenticators.
Authenticator
¶ Abstract authenticator class. Custom authentication methods should extend this class.
-
authenticate
()¶ Implementations of
Authenticator
should override this method.This will be called before a request handler is called, and should raise an
flask_rebar.errors.HttpJsonError
is authentication fails.Otherwise the return value is ignored.
Raises: flask_rebar.errors.Unauthorized
-
-
class
flask_rebar.
HeaderApiKeyAuthenticator
(header, name='sharedSecret')¶ Authenticates based on a small set of shared secrets, passed via a header.
This allows multiple client applications to be registered with their own keys. This also allows multiple keys to be registered for a single client application.
Parameters: - header (str) – The header where clients where client applications must include their secret.
- name (str) – A name for this authenticator. This should be unique across authenticators.
-
register_key
(key, app_name='default')¶ Register a client application’s shared secret.
Parameters: - app_name (str) – Name for the application. Since an application can have multiple shared secrets, this does not need to be unique.
- key (str) – The shared secret.
-
authenticate
()¶ Implementations of
Authenticator
should override this method.This will be called before a request handler is called, and should raise an
flask_rebar.errors.HttpJsonError
is authentication fails.Otherwise the return value is ignored.
Raises: flask_rebar.errors.Unauthorized
Swagger V2 Generation¶
-
class
flask_rebar.
SwaggerV2Generator
(host='localhost', schemes=(), consumes=('application/json', ), produces=('application/json', ), version='1.0.0', title='My API', description='', query_string_converter_registry=None, request_body_converter_registry=None, headers_converter_registry=None, response_converter_registry=None, tags=None, default_response_schema=<Error(many=False)>, authenticator_converter_registry=None)¶ Generates a v2.0 Swagger specification from a Rebar object.
Not all things are retrievable from the Rebar object, so this guy also needs some additional information to complete the job.
Parameters: - host (str) – Host name or ip of the API. This is not that useful for generating a static specification that will be used across multiple hosts (i.e. PlanGrid folks, don’t worry about this guy. We have to override it manually when initializing a client anyways.
- schemes (Sequence[str]) – “http”, “https”, “ws”, or “wss”. Defaults to empty. If left empty, the Swagger UI will infer the scheme from the document URL, ensuring that the “Try it out” buttons work.
- consumes (Sequence[str]) – Mime Types the API accepts
- produces (Sequence[str]) – Mime Types the API returns
- query_string_converter_registry (ConverterRegistry) –
- request_body_converter_registry (ConverterRegistry) –
- headers_converter_registry (ConverterRegistry) –
- response_converter_registry (ConverterRegistry) – ConverterRegistrys that will be used to convert Marshmallow schemas to the corresponding types of swagger objects. These default to the global registries.
- tags (Sequence[Tag]) – A list of tags used by the specification with additional metadata.
-
generate_swagger
(registry, host=None)¶ Generate a swagger definition json object. :param registry: :param host: :return:
-
generate
(registry, host=None, schemes=None, consumes=None, produces=None, sort_keys=True)¶ Generate a swagger specification from the provided registry
generate_swagger implements the SwaggerGeneratorI interface. But for backwards compatibility, we are keeping the similarly named generate signature.
Parameters: - registry (flask_rebar.rebar.HandlerRegistry) –
- host (str) – Overrides the initialized host
- schemes (Sequence[str]) – Overrides the initialized schemas
- consumes (Sequence[str]) – Overrides the initialized consumes
- produces (Sequence[str]) – Overrides the initialized produces
- sort_keys (bool) – Use OrderedDicts sorted by keys instead of dicts
Return type: dict
-
class
flask_rebar.
Tag
(name, description=None, external_docs=None)¶ Represents a Swagger “Tag Object”
Parameters: - name (str) – The name of the tag
- description (str) – A short description for the tag
- external_docs (ExternalDocumentation) – Additional external documentation for this tag
-
as_swagger
()¶ Create a Swagger representation of this object
Return type: dict
-
class
flask_rebar.
ExternalDocumentation
(url, description=None)¶ Represents a Swagger “External Documentation Object”
Parameters: - url (str) – The URL for the target documentation. Value MUST be in the format of a URL
- description (str) – A short description of the target documentation
-
as_swagger
()¶ Create a Swagger representation of this object
Return type: dict
-
flask_rebar.swagger_generation.
sets_swagger_attr
(attr)¶ Decorates a MarshmallowConverter method, marking it as an JSONSchema attribute setter.
Example usage:
class Converter(MarshmallowConverter): MARSHMALLOW_TYPE = String() @sets_swagger_attr('type') def get_type(obj, context): return 'string'
This converter receives instances of String and converts it to a JSONSchema object that looks like {‘type’: ‘string’}.
Parameters: attr (str) – The attribute to set
-
class
flask_rebar.swagger_generation.
ConverterRegistry
¶ Registry for MarshmallowConverters.
Schemas for responses, query strings, request bodies, etc. need to be converted differently. For example, response schemas as “dump”ed and request body schemas are “loaded”. For another example, query strings don’t support nesting.
This registry also allows for additional converters to be added for custom Marshmallow types.
-
register_type
(converter)¶ Registers a converter.
Parameters: converter (MarshmallowConverter) –
-
register_types
(converters)¶ Registers multiple converters.
Parameters: converters (iterable[MarshmallowConverter]) –
-
convert
(obj, openapi_version=2)¶ Converts a Marshmallow object to a JSONSchema dictionary.
Parameters: - obj (m.Schema|m.fields.Field|Validator) – The Marshmallow object to be converted
- openapi_version (int) – major version of OpenAPI to convert obj for
Return type: dict
-
Helpers¶
-
class
flask_rebar.
ResponseSchema
(only: Union[Sequence[str], Set[str], NoneType] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Union[Dict[KT, VT], NoneType] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Union[str, NoneType] = None)¶
-
flask_rebar.
RequestSchema
¶ alias of
marshmallow.schema.Schema
-
flask_rebar.
get_validated_args
()¶ Retrieve the result of validating/transforming an incoming request’s query string with the query_string_schema a handler was registered with.
Return type: dict
-
flask_rebar.
get_validated_body
()¶ Retrieve the result of validating/transforming an incoming request body with the request_body_schema a handler was registered with.
Return type: dict
-
flask_rebar.
marshal
(data, schema)¶ Dumps an object with the given marshmallow.Schema.
Raises: marshmallow.ValidationError if the given data fails validation of the schema.
-
flask_rebar.
response
(data, status_code=200, headers=None, mimetype=None)¶ Constructs a flask.jsonify response.
Parameters: - data (dict) – The JSON body of the response
- status_code (int) – HTTP status code to use in the response
- headers (dict) – Additional headers to attach to the response
- mimetype (str) – Default Content-Type response header
Return type: flask.Response
Exceptions¶
-
class
flask_rebar.errors.
HttpJsonError
(msg=None, additional_data=None)¶ Abstract base class for exceptions that will be cause and transformed into an appropriate HTTP error response with a JSON body.
These can be raised at any time during the handling of a request, and the Rebar extension will handling catching it and transforming it.
This class itself shouldn’t be used. Instead, use one of the subclasses.
Parameters: - msg (str) – A human readable message to be included in the JSON error response
- additional_data (dict) – Dictionary of additional keys and values to be set in the JSON body. Note that these keys and values are added to the root object of the response, not nested under “additional_data”.
-
class
flask_rebar.errors.
BadRequest
(msg=None, additional_data=None)¶ -
http_status_code
= 400¶
-
default_message
= 'Bad Request'¶
-
-
class
flask_rebar.errors.
PaymentRequired
(msg=None, additional_data=None)¶ -
http_status_code
= 402¶
-
default_message
= 'Payment Required'¶
-
-
class
flask_rebar.errors.
Forbidden
(msg=None, additional_data=None)¶ -
http_status_code
= 403¶
-
default_message
= 'Forbidden'¶
-
-
class
flask_rebar.errors.
NotFound
(msg=None, additional_data=None)¶ -
http_status_code
= 404¶
-
default_message
= 'Not Found'¶
-
-
class
flask_rebar.errors.
MethodNotAllowed
(msg=None, additional_data=None)¶ -
http_status_code
= 405¶
-
default_message
= 'Method Not Allowed'¶
-
-
class
flask_rebar.errors.
NotAcceptable
(msg=None, additional_data=None)¶ -
http_status_code
= 406¶
-
default_message
= 'Not Acceptable'¶
-
-
class
flask_rebar.errors.
ProxyAuthenticationRequired
(msg=None, additional_data=None)¶ -
http_status_code
= 407¶
-
default_message
= 'Proxy Authentication Required'¶
-
-
class
flask_rebar.errors.
RequestTimeout
(msg=None, additional_data=None)¶ -
http_status_code
= 408¶
-
default_message
= 'Request Timeout'¶
-
-
class
flask_rebar.errors.
Conflict
(msg=None, additional_data=None)¶ -
http_status_code
= 409¶
-
default_message
= 'Conflict'¶
-
-
class
flask_rebar.errors.
Gone
(msg=None, additional_data=None)¶ -
http_status_code
= 410¶
-
default_message
= 'Gone'¶
-
-
class
flask_rebar.errors.
LengthRequired
(msg=None, additional_data=None)¶ -
http_status_code
= 411¶
-
default_message
= 'Length Required'¶
-
-
class
flask_rebar.errors.
PreconditionFailed
(msg=None, additional_data=None)¶ -
http_status_code
= 412¶
-
default_message
= 'Precondition Failed'¶
-
-
class
flask_rebar.errors.
RequestEntityTooLarge
(msg=None, additional_data=None)¶ -
http_status_code
= 413¶
-
default_message
= 'Request Entity Too Large'¶
-
-
class
flask_rebar.errors.
RequestUriTooLong
(msg=None, additional_data=None)¶ -
http_status_code
= 414¶
-
default_message
= 'Request URI Too Long'¶
-
-
class
flask_rebar.errors.
UnsupportedMediaType
(msg=None, additional_data=None)¶ -
http_status_code
= 415¶
-
default_message
= 'Unsupported Media Type'¶
-
-
class
flask_rebar.errors.
RequestedRangeNotSatisfiable
(msg=None, additional_data=None)¶ -
http_status_code
= 416¶
-
default_message
= 'Requested Range Not Satisfiable'¶
-
-
class
flask_rebar.errors.
ExpectationFailed
(msg=None, additional_data=None)¶ -
http_status_code
= 417¶
-
default_message
= 'Expectation Failed'¶
-
-
class
flask_rebar.errors.
UnprocessableEntity
(msg=None, additional_data=None)¶ -
http_status_code
= 422¶
-
default_message
= 'Unprocessable Entity'¶
-
-
class
flask_rebar.errors.
InternalError
(msg=None, additional_data=None)¶ -
http_status_code
= 500¶
-
default_message
= 'Internal Server Error'¶
-
-
class
flask_rebar.errors.
NotImplemented
(msg=None, additional_data=None)¶ -
http_status_code
= 501¶
-
default_message
= 'Not Implemented'¶
-
-
class
flask_rebar.errors.
BadGateway
(msg=None, additional_data=None)¶ -
http_status_code
= 502¶
-
default_message
= 'Bad Gateway'¶
-