Developer Interface

This part of the documentation covers all the interfaces of Arrested.

API

class arrested.api.ArrestedAPI(app=None, url_prefix='', before_all_hooks=None, after_all_hooks=None)[source]

ArrestedAPI defines versions of your api on which Endpoint are registered It acts like Flasks Blueprint object with a few minor differences.

Constructor to create a new ArrestedAPI object.

Parameters:
  • app -- Flask app object.
  • url_prefix -- Specify a url prefix for all resources attached to this API. Typically this is used for specifying the API version.
  • before_all_hooks -- A list containing funcs which will be called before every request made to any resource registered on this Api.
  • after_all_hooks -- A list containing funcs which will be called after every request made to any resource registered on this Api.

Usage:

app = Flask(__name__, url_prefix='/v1')
api_v1 = ArrestedAPI(app)
init_app(app)[source]

Initialise the ArrestedAPI object by storing a pointer to a Flask app object. This method is typically used when initialisation is deferred.

Parameters:app -- Flask application object

Usage:

app = Flask(__name__)
ap1_v1 = ArrestedAPI()
api_v1.init_app(app)
register_all(resources)[source]

Register each resource from an iterable.

Params resources:
 An iterable containing Resource objects

Usage:

characters_resource = Resource(
    'characters', __name__, url_prefix='/characters'
)
planets_resource = Resource('planets', __name__, url_prefix='/planets')
api_v1 = ArrestedAPI(prefix='/v1')
api_v1.register_all([characters_resource, planets_resource])
register_resource(resource, defer=False)[source]

Register a Resource blueprint object against the Flask app object.

Parameters:
  • resource -- Resource or flask.Blueprint object.
  • defer -- Optionally specify that registering this resource should be deferred. This option is useful when users are creating their Flask app instance via a factory.

Deferred resource registration

Resources can optionally be registered in a deferred manner. Simply pass defer=True to ArrestedAPI.register_resource to attach the resource to the API without calling register_blueprint.

This is useful when you're using the factory pattern for creating your Flask app object as demonstrated below. Deferred resource will not be registered until the ArrestedAPI instance is initialised with the Flask app object.

Usage:

api_v1 = ArrestedAPI(prefix='/v1')
characters_resource = Resource(
    'characters', __name__, url_prefix='/characters'
)
ap1_v1.register_resource(characters_resource, defer=True)

def create_app():

    app = Flask(__name__)
    api_v1.init_app(app) # deferred resources are now registered.

Resource

class arrested.resource.Resource(name, import_name, api=None, before_all_hooks=None, after_all_hooks=None, *args, **kwargs)[source]

Resource extends Flasks existing Blueprint object and provides some utilty methods that make registering Endpoint simpler.

Construct a new Reosurce blueprint. In addition to the normal Blueprint options, Resource accepts kwargs to set request middleware.

Parameters:
  • api -- API instance being the resource is being registered against.
  • before_all_hooks -- A list of middleware functions that will be applied before every request.
  • after_all_hooks -- A list of middleware functions that will be applied after every request.

Middleware

Arrested supports applying request middleware at every level of the application stack. Resource middleware will be applied for every Endpoint registered on that Resource.

character_resource = Resource(
    'characters', __name__,
    url_prefix='/characters',
    before_all_hooks=[log_request]
)

Arrested request middleware works differently from the way Flask middleware does. Middleware registered at the Resource and API level are consumed by the arrested.Endpoint.dispatch_request rather than being fired via the Flask app instance. This is so we can pass the instance of the endpoint handling the request to each piece of middleware registered on the API or Resource.

def api_key_required(endpoint):

    if request.args.get('api_key', None) is None:
        endpoint.return_error(422)
    else:
        get_client(request.args['api_key'])

character_resource = Resource(
    'characters', __name__,
    url_prefix='/characters',
    before_all_hooks=[api_key_required]
)

Please note, Flask's normal App and Blueprint middleware can still be used as normal, it just doesn't recieve the instance of the endpoint registered to handle the request.

add_endpoint(endpoint)[source]

Register an Endpoint aginst this resource.

Parameters:endpoint -- Endpoint API Endpoint class

Usage:

foo_resource = Resource('example', __name__)
class MyEndpoint(Endpoint):

    url = '/example'
    name = 'myendpoint'

foo_resource.add_endpoint(MyEndpoint)
init_api(api)[source]

Registered the instance of ArrestedAPI the Resource is being registered against.

Parameters:api -- API instance being the resource is being registered against.

Endpoint

class arrested.endpoint.Endpoint[source]

The Endpoint class represents the HTTP methods that can be called against an Endpoint inside of a particular resource.

after_all_hooks = []

A list of functions called after all requests are dispatched

after_delete_hooks = []

A list of functions called after DELETE requests are dispatched

after_get_hooks = []

A list of functions called after GET requests are dispatched

after_patch_hooks = []

A list of functions called after PATCH requests are dispatched

after_post_hooks = []

A list of functions called after POST requests are dispatched

after_put_hooks = []

A list of functions called after PUT requests are dispatched

as_view(name, *class_args, **class_kwargs)

Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the dispatch_request method on it.

The arguments passed to as_view are forwarded to the constructor of the class.

before_all_hooks = []

A list of functions called before any specific request handler methods are called

before_delete_hooks = []

A list of functions called before DELETE requests are dispatched

before_get_hooks = []

A list of functions called before GET requests are dispatched

before_patch_hooks = []

A list of functions called before PATCH requests are dispatched

before_post_hooks = []

A list of functions called before POST requests are dispatched

before_put_hooks = []

A list of functions called before PUT requests are dispatched

delete(*args, **kwargs)[source]

Handle Incoming DELETE requests and dispatch to handle_delete_request method.

dispatch_request(*args, **kwargs)[source]

Dispatch the incoming HTTP request to the appropriate handler.

get(*args, **kwargs)[source]

Handle Incoming GET requests and dispatch to handle_get_request method.

classmethod get_name()[source]

Returns the user provided name or the lower() class name for use when registering the Endpoint with a Resource.

Returns:registration name for this Endpoint.
Return type:string
get_request_handler()[source]

Return the Endpoints defined Endpoint.request_handler.

Returns:A instance of the Endpoint specified RequestHandler.
Return type:RequestHandler
get_request_handler_params(**params)[source]

Return a dictionary of options that are passed to the specified RequestHandler.

Returns:Dictionary of RequestHandler config options.
Return type:dict
get_response_handler()[source]

Return the Endpoints defined Endpoint.response_handler.

Returns:A instance of the Endpoint specified ResonseHandler.
Return type:ResponseHandler
get_response_handler_params(**params)[source]

Return a dictionary of options that are passed to the specified ResponseHandler.

Returns:Dictionary of ResponseHandler config options.
Return type:dict
make_response(rv, status=200, headers=None, mime='application/json')[source]

Create a response object using the flask.Response class.

Parameters:
  • rv -- Response value. If the value is not an instance of werkzeug.wrappers.Response it will be converted into a Response object.
  • status -- specify the HTTP status code for this response.
  • mime -- Specify the mimetype for this request.
  • headers -- Specify dict of headers for the response.
methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']

list containing the permitted HTTP methods this endpoint accepts

name = None

The name used to register this endpoint with Flask's url_map

patch(*args, **kwargs)[source]

Handle Incoming PATCH requests and dispatch to handle_patch_request method.

post(*args, **kwargs)[source]

Handle Incoming POST requests and dispatch to handle_post_request method.

process_after_request_hooks(resp)[source]

Process the list of before_{method}_hooks and the before_all_hooks. The hooks will be processed in the following order

1 - any after_{method}_hooks defined on the arrested.Endpoint object 2 - any after_all_hooks defined on the arrested.Endpoint object 2 - any after_all_hooks defined on the arrested.Resource object 4 - any after_all_hooks defined on the arrested.ArrestedAPI object

process_before_request_hooks()[source]

Process the list of before_{method}_hooks and the before_all_hooks. The hooks will be processed in the following order

1 - any before_all_hooks defined on the arrested.ArrestedAPI object 2 - any before_all_hooks defined on the arrested.Resource object 3 - any before_all_hooks defined on the arrested.Endpoint object 4 - any before_{method}_hooks defined on the arrested.Endpoint object

put(*args, **kwargs)[source]

Handle Incoming PUT requests and dispatch to handle_put_request method.

request_handler

A RequestHandler class

alias of RequestHandler

response_handler

A ResponseHandler class

alias of ResponseHandler

return_error(status, payload=None)[source]

Error handler called by request handlers when an error occurs and the request should be aborted.

Usage:

def handle_post_request(self, *args, **kwargs):

    self.request_handler = self.get_request_handler()
    try:
        self.request_handler.process(self.get_data())
    except SomeException as e:
        self.return_error(400, payload=self.request_handler.errors)

    return self.return_create_response()
url = ''

The URL this endpoint is mapped against. This will build on top of any url_prefix defined at the API and Resource level

Mixins

class arrested.mixins.GetListMixin[source]

Base ListMixin class that defines the expected API for all ListMixins

get_objects()[source]
handle_get_request()[source]

Handle incoming GET request to an Endpoint and return an array of results by calling GetListMixin.get_objects.

See also

GetListMixin.get_objects Endpoint.get

list_response(status=200)[source]

Pull the processed data from the response_handler and return a response.

Parameters:status -- The HTTP status code returned with the response
class arrested.mixins.CreateMixin[source]

Base CreateMixin class that defines the expected API for all CreateMixins

create_response(status=201)[source]

Generate a Response object for a POST request. By default, the newly created object will be passed to the specified ResponseHandler and will be serialized as the response body.

handle_post_request()[source]

Handle incoming POST request to an Endpoint and marshal the request data via the specified RequestHandler. CreateMixin.save_object. is then called and must be implemented by mixins implementing this interfce.

See also

CreateMixin.save_object Endpoint.post

save_object(obj)[source]

Called by CreateMixin.handle_post_request ater the incoming data has been marshalled by the RequestHandler.

Parameters:obj -- The marhsaled object from RequestHandler.
class arrested.mixins.ObjectMixin[source]

Mixin that provides an interface for working with single data objects

get_object()[source]

Called by GetObjectMixin.handle_get_request. Concrete classes should implement this method and return object typically by id.

Raises:NotImplementedError
obj

Returns the value of ObjectMixin.get_object and sets a private property called _obj. This property ensures the logic around allow_none is enforced across Endpoints using the Object interface.

Raises:werkzeug.exceptions.BadRequest
Returns:The result of :meth:ObjectMixin.get_object`
object_response(status=200)[source]

Generic response generation for Endpoints that return a single serialized object.

Parameters:status -- The HTTP status code returned with the response
Returns:Response object
class arrested.mixins.GetObjectMixin[source]

Base GetObjectMixins class that defines the expected API for all GetObjectMixins

handle_get_request()[source]

Handle incoming GET request to an Endpoint and return a single object by calling GetListMixin.get_object.

See also

GetListMixin.get_objects Endpoint.get

class arrested.mixins.PutObjectMixin[source]

Base PutObjectMixins class that defines the expected API for all PutObjectMixin

handle_put_request()[source]
put_request_response(status=200)[source]

Pull the processed data from the response_handler and return a response.

Parameters:status -- The HTTP status code returned with the response
update_object(obj)[source]

Called by PutObjectMixin.handle_put_request ater the incoming data has been marshalled by the RequestHandler.

Parameters:obj -- The marhsaled object from RequestHandler.
class arrested.mixins.PatchObjectMixin[source]

Base PatchObjectMixin class that defines the expected API for all PatchObjectMixin

handle_patch_request()[source]
patch_object(obj)[source]

Called by PatchObjectMixin.handle_patch_request ater the incoming data has been marshalled by the RequestHandler.

Parameters:obj -- The marhsaled object from RequestHandler.
patch_request_response(status=200)[source]

Pull the processed data from the response_handler and return a response.

Parameters:status -- The HTTP status code returned with the response
class arrested.mixins.DeleteObjectMixin[source]

Base DeletehObjecttMixin class that defines the expected API for all DeletehObjecttMixins.

delete_object(obj)[source]

Called by DeleteObjectMixin.handle_delete_request.

Parameters:obj -- The marhsaled object being deleted.
delete_request_response(status=204)[source]

Pull the processed data from the response_handler and return a response.

Parameters:status -- The HTTP status code returned with the response
handle_delete_request()[source]

Handlers

class arrested.handlers.Handler(endpoint, payload_key='payload', **params)[source]
handle(data, **kwargs)[source]

Invoke the handler to process the provided data. Concrete classes should override this method to provide specific capabilties for the choosen method of marshaling and serializing data.

Parameters:data -- The data to be processed by the Handler.
Returns:The data processed by the Handler
Return type:mixed

Here's an example of a RequestHandler integrating with the Kim library.

def handle(self, data):
    try:
        if self.many:
            return self.mapper.many(raw=self.raw,
                                    **self.mapper_kwargs)                             .marshal(data, role=self.role)
        else:
            return self.mapper(data=data, raw=self.raw,
                               **self.mapper_kwargs)                             .marshal(role=self.role)
    except MappingInvalid as e:
        self.errors = e.errors
process(data=None, **kwargs)[source]

Process the provided data and invoke Handler.handle method for this Handler class.

Params data:The data being processed.
Returns:self
Return type:Handler
def post(self, *args, **kwargs):
    self.request = self.get_request_handler()
    self.request.process(self.get_data())
    return self.get_create_response()
class arrested.handlers.JSONResponseMixin[source]

Provides handling for serializing the response data as a JSON string.

get_response_data()[source]

serialzie the response data and payload_key as a JSON string.

Returns:JSON serialized string
Return type:bytes
class arrested.handlers.JSONRequestMixin[source]

Provides handling for fetching JSON data from the FLask request object.

get_request_data()[source]

Pull JSON from the Flask request object.

Returns:Deserialized JSON data.
Return type:mixed
Raises:flask.exceptions.JSONBadRequest
class arrested.handlers.RequestHandler(endpoint, payload_key='payload', **params)[source]

Basic default RequestHandler that expects the will pull JSON from the Flask request object and return it.

process(data=None)[source]

Fetch incoming data from the Flask request object when no data is supplied to the process method. By default, the RequestHandler expects the incoming data to be sent as JSON.

class arrested.handlers.ResponseHandler(endpoint, payload_key='payload', **params)[source]

Basic default ResponseHanlder that expects the data passed to it to be JSON serializable without any modifications.

Exceptions

exception arrested.exceptions.ArrestedException[source]