API

This section covers all the interfaces of RESTArt.

RESTArt Object

class restart.api.RESTArt

The class that represents the RESTArt API and acts as the central object.

add_rule(resource_class, uri, endpoint, methods=None, actions=None)

Register a resource for the given URI rule.

Parameters:
  • resource_class – the resource class.
  • uri – the URI registered. Werkzeug-style converters are supported here. See Rule Format for more information.
  • endpoint – the endpoint for the URI.
  • methods – a sequence of allowed HTTP methods. If not specified, all methods are allowed.
  • actions – a dictionary with the specific action mapping pairs used to update the default ACTION_MAP. If not specified, the default ACTION_MAP will be used. See Configuration for more information.
add_rule_with_format_suffix(resource_class, uri, endpoint, methods=None, actions=None, format_suffix='disabled')

Register a resource for the given URI rule with a possible format suffix.

Parameters:format_suffix – a string indicating whether or how to support content negotiation via format suffixes on URIs. If specified, its value must be ‘disabled’ (not supported), ‘optional’ (supported and optional) or ‘mandatory’ (supported and mandatory). If not specified, defaults to ‘disabled’.

See add_rule() for the meanings of other parameters.

register(cls=None, prefix=None, pk='<pk>', list_actions=None, item_actions=None, format_suffix='disabled')

A special decorator that is used to register a plural resource. See Routing for more information.

Important note:

Unlike the route() and add_rule() methods, ‘OPTIONS’ is always allowed implicitly in register() to handle potential CORS. In order to achieve the same purpose, you must add ‘OPTIONS’ into the methods parameter explicitly when using the route() and add_rule() methods.
Parameters:
  • cls – the class that will be decorated.
  • prefix – the URI prefix for the resource. If not specified, the resource name with a leading slash will be used. For example, the prefix will be ‘/todos’ if the resource name is ‘todos’.
  • pk – the primary key name used to identify a specific resource. Werkzeug-style converters are supported here. See Rule Format for more information.
  • list_actions – the action mapping pairs for the list-part URI (the URI without the primary key, see Plural Resources for more information). If not specified, the default ACTION_MAP will be used. See Configuration for more information.
  • item_actions – the action mapping pairs for the item-part URI (the URI with the primary key, see Plural Resources for more information). If not specified, the default ACTION_MAP will be used. See Configuration for more information.
  • format_suffix – see add_rule_with_format_suffix().
route(cls=None, uri=None, endpoint=None, methods=None, actions=None, format_suffix='disabled')

A decorator that is used to register a resource for a given URI rule. See Routing for more information.

Parameters:
  • cls – the class that will be decorated.
  • uri – the URI registered. Werkzeug-style converters are supported here. See Rule Format for more information. If not specified, the resource name with a leading slash will be used. For example, the uri will be ‘/todos’ if the resource name is ‘todos’.
  • endpoint – the endpoint for the URI. If not specified, the resource name will be used.
  • methods – a sequence of allowed HTTP methods. If not specified, all methods are allowed.
  • actions – a dictionary with the specific action mapping pairs used to update the default ACTION_MAP. If not specified, the default ACTION_MAP will be used. See Configuration for more information.
  • format_suffix – see add_rule_with_format_suffix().
rules

A dictionary of all registered rules, which is a mapping from URI endpoints to URI rules. See Rule for more information about URI rules.

class restart.api.Rule(uri, methods, handler)

A simple class that holds a URI rule.

Parameters:
  • uri – the URI.
  • methods – the allowed HTTP methods for the URI.
  • handler – the handler for the URI.

Resource Object

class restart.resource.Resource(action_map)

The core class that represents a REST resource.

Parameters:action_map – the mapping of request methods to resource actions.
dispatch_request(request, *args, **kwargs)

Does the request dispatching. Matches the HTTP method and return the return value of the bound action.

Parameters:
  • request – the request object.
  • args – the positional arguments captured from the URI.
  • kwargs – the keyword arguments captured from the URI.
find_action(request)

Find the appropriate action according to the request method.

Parameters:request – the request object.
get_parser_context(request, args, kwargs)

Return a dictionary that represents a parser context.

Parameters:
  • request – the request object.
  • args – the positional arguments captured from the URI.
  • kwargs – the keyword arguments captured from the URI.
get_renderer_context(request, args, kwargs, response)

Return a dictionary that represents a renderer context.

Parameters:
  • request – the request object.
  • args – the positional arguments captured from the URI.
  • kwargs – the keyword arguments captured from the URI.
  • response – the response object.
handle_exception(exc)

Handle any exception that occurs, by returning an appropriate response, or re-raising the error.

Parameters:exc – the exception to be handled.
http_method_not_allowed(request, *args, **kwargs)

The default action handler if the corresponding action for request.method is not implemented.

See dispatch_request() for the meanings of the parameters.

log_exception(exc)

Logs an exception with ERROR level.

Parameters:exc – the exception to be logged.
log_message(msg)

Logs a message with DEBUG level.

Parameters:msg – the message to be logged.
logger

A logging.Logger object for this API.

make_response(rv)

Converts the return value to a real response object that is an instance of Response.

The following types are allowed for rv:

Response the object is returned unchanged
str the string becomes the response body
unicode the unicode string becomes the response body
tuple A tuple in the form (data, status) or (data, status, headers) where data is the response body, status is an integer and headers is a dictionary with header values.
negotiator_class

alias of Negotiator

perform_action(*args, **kwargs)

Perform the appropriate action. Also apply all possible process_* methods of middleware instances in self.middlewares.

During request phase:

process_request() methods are called on each request, before RESTArt calls the action, in order.

It should return None or any other value that make_response can recognize. If it returns None, RESTArt will continue processing the request, executing any other process_request() and, then, the action. If it returns any other value (e.g. a Response object), RESTArt won’t bother calling any other middleware or the action.

During response phase:

process_response() methods are called on all responses before they’are returned to the client, in reverse order.

It must return a value that can be converted to a Response object by make_response. It could alter and return the given response, or it could create and return a brand-new value.

Unlike process_request() methods, the process_response() method is always called, even if the process_request() of the same middleware were skipped (because an earlier middleware method returned a Response).

Parameters:
  • args – a list of positional arguments that will be passed to the action.
  • kwargs – a dictionary of keyword arguments that will be passed to the action.

Request Objects

class restart.request.Request(initial_request)

The base request class used in RESTArt.

Parameters:initial_request – the initial request, which is framework-specific.
get_args()

Get the request URI parameters.

get_auth()

Get the request authorization data.

get_environ()

Get the request WSGI environment.

get_headers()

Get the request headers.

get_method()

Get the request method.

get_path()

Get the request path.

get_scheme()

Get the request scheme.

get_stream()

Get the request stream.

get_uri()

Get the request URI.

parse(negotiator, parser_classes, parser_context=None)

Return a request object with the data parsed, which is a dictionary. If the request payload is empty, the parsed data will be an empty dictionary.

Parameters:
  • negotiator – the negotiator object used to select the proper parser, which will be used to parse the request payload.
  • parser_classes – the parser classes to select from. See Parser Objects for information about parsers.
  • parser_context – a dictionary containing extra context data that can be useful to the parser.
class restart.request.WerkzeugRequest(initial_request)

The Werkzeug-specific request class.

get_args()

Get the request URI parameters from the Werkzeug-specific request object.

get_auth()

Get the request authorization data from the Werkzeug-specific request object.

get_environ()

Get the WSGI environment from the Werkzeug-specific request object.

get_headers()

Get the request headers from the Werkzeug-specific request object.

get_method()

Get the request method from the Werkzeug-specific request object.

get_path()

Get the request path from the Werkzeug-specific request object.

get_scheme()

Get the request scheme from the Werkzeug-specific request object.

get_stream()

Get the request stream from the Werkzeug-specific request object.

get_uri()

Get the request URI from the Werkzeug-specific request object.

Response Objects

class restart.response.Response(data, status=200, headers=None)

The base response class used in RESTArt.

Parameters:
  • data – the response body.
  • status – an integer that represents an HTTP status code.
  • headers – a dictionary with HTTP header values.
get_specific_response()

Get the framework-specific response.

render(negotiator, renderer_classes, format_suffix, renderer_context=None)

Return a response object with the data rendered.

Parameters:
  • negotiator – the negotiator object used to select the proper renderer, which will be used to render the response payload.
  • renderer_classes – the renderer classes to select from. See Renderer Objects for information about renderers.
  • format_suffix – the format suffix of the request uri.
  • renderer_context – a dictionary containing extra context data that can be useful to the renderer.
class restart.response.WerkzeugResponse(data, status=200, headers=None)

The Werkzeug-specific response class.

get_specific_response()

Get the Werkzeug-specific response.

Negotiator Object

class restart.negotiator.Negotiator

The class used to select the proper parser and renderer.

select_parser(parser_classes, content_type)

Select the proper parser class.

Parameters:
  • parser_classes – the parser classes to select from.
  • content_type – the target content type.
select_renderer(renderer_classes, format_suffix)

Select the proper renderer class.

Note:
For simplicity, the content-negotiation here is only based on the format suffix specified in the request uri. The more standard (and also complex) Accept header is ignored.
Parameters:
  • renderer_classes – the renderer classes to select from.
  • format_suffix – the format suffix of the request uri.

Parser Objects

class restart.parsers.Parser

The base parser class.

parse(stream, content_type, content_length, context=None)

Parse the stream.

Parameters:
  • stream – the stream to be parsed.
  • content_type – the content type of the request payload.
  • content_length – the content length of the request payload.
  • context – a dictionary containing extra context data that can be useful for parsing.
class restart.parsers.JSONParser

The parser class for JSON data.

parse(stream, content_type, content_length, context=None)

Parse the stream as JSON.

Parameters:
  • stream – the stream to be parsed.
  • content_type – the content type of the request payload.
  • content_length – the content length of the request payload.
  • context – a dictionary containing extra context data that can be useful for parsing.
class restart.parsers.MultiPartParser

The parser class for multipart form data, which may include file data.

parse(stream, content_type, content_length, context=None)

Parse the stream as a multipart encoded form.

Parameters:
  • stream – the stream to be parsed.
  • content_type – the content type of the request payload.
  • content_length – the content length of the request payload.
  • context – a dictionary containing extra context data that can be useful for parsing.
class restart.parsers.URLEncodedParser

The parser class for form data.

parse(stream, content_type, content_length, context=None)

Parse the stream as a URL encoded form.

Parameters:
  • stream – the stream to be parsed.
  • content_type – the content type of the request payload.
  • content_length – the content length of the request payload.
  • context – a dictionary containing extra context data that can be useful for parsing.

Renderer Objects

class restart.renderers.Renderer

The base renderer class.

render(data, context=None)

Render data.

Parameters:
  • data – the data to be rendered.
  • context – a dictionary containing extra context data that can be useful for rendering.
class restart.renderers.JSONRenderer

The JSON renderer class.

render(data, context=None)

Render data into JSON.

Parameters:
  • data – the data to be rendered.
  • context – a dictionary containing extra context data that can be useful for rendering.

Adapter Objects

class restart.adapter.Adapter(api)

The class used to adapt the RESTArt API to a specific framework.

Parameters:api – the RESTArt API to adapt.
adapt_handler(handler, *args, **kwargs)

Adapt the request object and the response object for the handler function.

Parameters:
  • handler – the handler function to be adapted.
  • args – a list of positional arguments that will be passed to the handler.
  • kwargs – a dictionary of keyword arguments that will be passed to the handler.
adapt_rules(rules)

Adapt the rules to be framework-specific.

get_embedded_rules()

Get the framework-specific rules used to be embedded into an existing or legacy application.

wsgi_app(environ, start_response)

The actual framework-specific WSGI application.

See wsgi_app() for the meanings of the parameters.

class restart.adapter.WerkzeugAdapter(*args, **kwargs)
adapt_handler(handler, request, *args, **kwargs)

Adapt the request object and the response object for the handler function.

Parameters:
  • handler – the handler function to be adapted.
  • request – the Werkzeug request object.
  • args – a list of positional arguments that will be passed to the handler.
  • kwargs – a dictionary of keyword arguments that will be passed to the handler.
get_embedded_rules()

Get the Werkzeug-specific rules used to be embedded into an existing or legacy application.

Example:

# The existing Werkzeug application,
# whose URL map is `app.url_map`
app = ...
...

# The RESTArt API
from restart.api import RESTArt
api = RESTArt()
...

# Embed RESTArt into Werkzeug
from restart.serving import Service
service = Service(api)
for rule in service.embedded_rules:
    app.url_map.add(rule)
wsgi_app(environ, start_response)

The actual Werkzeug-specific WSGI application.

See wsgi_app() for the meanings of the parameters.

Service Object

class restart.serving.Service(api, adapter_class=<class 'restart.adapter.WerkzeugAdapter'>)

The service class for serving the RESTArt API.

Parameters:
  • api – the RESTArt API.
  • adapter_class – the class that is used to adapt the api object. See WerkzeugAdapter for more information.
__call__(environ, start_response)

Make the Service object itself to be a WSGI application.

Parameters:
  • environ – a WSGI environment.
  • start_response – a callable accepting a status code, a list of headers and an optional exception context to start the response
embedded_rules

The framework-specific rules used to be embedded into an existing or legacy application.

rules

The framework-specific API rules.

run(host=None, port=None, debug=None, **options)

Runs the API on a local development server.

Parameters:
  • host – the hostname to listen on. Set this to ‘0.0.0.0’ to have the server available externally as well. Defaults to ‘127.0.0.1’.
  • port – the port of the webserver. Defaults to 5000.
  • debug – if given, enable or disable debug mode.
  • options – the options to be forwarded to the underlying Werkzeug server. See werkzeug.serving.run_simple() for more information.
wsgi_app(environ, start_response)

The actual WSGI application.

Parameters:
  • environ – a WSGI environment.
  • start_response – a callable accepting a status code, a list of headers and an optional exception context to start the response

Utilities

class restart.utils.locked_cached_property(method=None, name=None)

A decorator that converts a method into a lazy property.

The method wrapped is called the first time to retrieve the result and then that calculated result is used the next time you access the value.

This decorator has a lock for thread safety.

Inspired by Flask.

Parameters:
  • method – the method that will be decorated.
  • name – the name of the cached property, which holds the calculated result. If not specified, the <method-name> (the name of the decorated method) will be used.
class restart.utils.classproperty(fget, *args, **kwargs)

A decorator that converts a method into a read-only class property.

Note:
You ought not to set the value of classproperty-decorated attributes! The result of the behavior is undefined.
class restart.utils.locked_cached_classproperty(method=None, name=None)

The lazy version of classproperty, which converts a method into a lazy class property.

Parameters:
  • method – the method that will be decorated.
  • name – the name of the cached class property, which holds the calculated result. If not specified, the name with the form of _locked_cached_classproperty_<method-name> will be used.
restart.utils.load_resources(module_names)

Import all modules in module_names to load resources.

Example usage:

load_resources(['yourapi.resources.users.resource'])
load_resources(['yourapi.resources.orders.resource'])

# the equivalent of the above two lines
load_resources(['yourapi.resources.*.resource'])
restart.utils.expand_wildcards(module_name)

Expand the wildcards in module_name based on sys.path.

Suppose the directory structure of “yourapi” is as below:

yourapi
|-- __init__.py
`-- resources
    |-- users
    |   |-- __init__.py
    |   `-- resource.py
    `-- orders
        |-- __init__.py
        `-- resource.py

Then:

expand_wildcards('yourapi.resources.*.resource')
=>
['yourapi.resources.users.resource',
 'yourapi.resources.orders.resource']
restart.utils.make_location_header(request, pk)

Make the Location header for the newly-created resource.

Parameters:
  • request – the POST request object.
  • pk – the primary key of the resource.