REST Toolkit 1.0 documentation

API documentation

«  Philosophy   ::   Contents   ::   Comparison with other frameworks  »

API documentation

rest_toolkit

rest_toolkit.includeme(config)

Configure basic REST settings for a Pyramid application.

You should not call this function directly, but use pyramid.config.Configurator.include() to initialise the REST toolkit.

1
2
config = Configurator()
config.include('rest_toolkit')
rest_toolkit.quick_serve(sql_session_factory=None, port=8080)

Start a HTTP server for your REST service.

This function provides quick way to run a webserver for your REST service. The webserver will listen on port 8080 on all IP addresses of the local machine.

If you need to configure the underlying Pyramid system, or you want to use a different HTTP server you will need to create the WSGI application yourself. Instead of using quick_serve you will need to do something like this:

1
2
3
4
5
6
7
8
from pyramid.config import Configurator
from wsgiref.simple_server import make_server

config = Configurator()
config.include('rest_toolkit')
config.scan()
app = config.make_wsgi_app()
make_server('0.0.0.0', 8080, app).serve_forever()
Parameters:
  • sql_session_factory – A factory function to return a SQLAlchemy session. This is generally a scoped_session instance, and commonly called Session or DBSession.
  • port (int) – TCP port to use for HTTP server.
class rest_toolkit.resource(route_path, route_name=None, create_permission=None, read_permission=None, update_permission=None, delete_permission=None, **view_arguments)

Configure a REST resource.

This decorator must be used to declare REST resources.

1
2
3
4
5
6
from rest_toolkit import resource

@resource('/users/{id}')
class User:
    def __init__(self, request):
        self.user_id = request.matchdict['id']
Parameters:
  • route_path

    The URL route pattern to use for the resource.

    For more information on route patterns please see the Pyramid route pattern syntax documentation.

  • route_name

    The name to use for the route.

    This may be needed if you want to generate URLs to resources using request.route_url().

  • create_permission

    Permission for the default create view.

    If no create permission is specified all users, including anonymous visitors, are allowed to issue POST requests for the resource.

    This permission is only applied to the default POST view. If you specify a custom POST view you need to specify the permission in the POST decorator call.

  • read_permission

    Permission for the default read view.

    If no read permission is specified all users, including anonymous visitors, are allowed to issue GET requests for the resource.

    This permission is only applied to the default GET view. If you specify a custom GET view you need to specify the permission in the GET decorator call.

  • update_permission

    Permission for default update views.

    If no update permission is specified all users, including anonymous visitors, are allowed to issue PATCH and PUT requests for the resource.

    This permission is only applied to the default views. If you specify a custom PATCH or PUT view you need to specify the permission in the decorator call.

  • delete_permission

    Permission for the default delete view.

    If no delete permission is specified all users, including anonymous visitors, are allowed to issue DELETE requests for the resource.

    This permission is only applied to the default DELETE view. If you specify a custom DELETE view you need to specify the permission in the DELETE decorator call.

class rest_toolkit.ViewDecorator(**kw)

Base class for HTTP request method decorators for resources.

This class should never be used directly. It is used internally to create the DELETE, GET, OPTIONS, PATCH, POST and PUT decorators for resources classes when the resource() decorator is used.

1
2
3
4
@MyResource.GET()
def get_view_for_my_resource(resource, request):
    '''Handle GET requests for MyResource.
    '''
class rest_toolkit.ControllerDecorator(name, request_method='POST', **kw)

Base class for controller views for resources.

This class should never be used directly. It is used internally to create the controller`decorator for resources classes when the :py:func:`resource decorator is used.

1
2
3
4
@MyResource.controller('frobnicate')
def frobnicate_my_resource(resource, request):
    '''Handle POST requests to ``/myresource/frobnicate``
    '''

rest_toolkit.abc

class rest_toolkit.abc.DeletableResource

Base class for resources using the default DELETE views.

If a resource class is derived from this class it must implement the dlete() method. Doing this will automatically enable the default DELETE view from rest_toolkit.

delete()

Delete the resource.

This method must delete the resource, or mark it as deleted, so that it is no longer accessible through the REST API.

class rest_toolkit.abc.EditableResource

Base class for resources using the default PATCH and PUT views.

If a resource class is derived from this class it must implement the to_dict(), validate() and update_from_dict() methods. Doing this will automatically enable the default GET, PATCH and PUT views from rest_toolkit.

complete_partial_data(data)

Complete partial object data.

This method will be used by the validation extension to create a complete data overview from partial information, as submitted in a PATCH request, before trying to validate it.

Parameters:data (dict) – The partial data to extend. The data is usually taken directly from a PATCH request. This dictionary will not be modified.
Return type:dict
Returns:a new dictionary with the complete data for the resource.
to_dict()

Generate a (JSON-compatible) dictionary with resource data.

This method is used by the default GET, PATCH and PUT views to generate the data for the response.

update_from_dict(data, replace)

Update a resource.

Parameters:
  • data (dict) – The data to validate. The data is usually taken directly from JSON send by a client.
  • replace (bool) – Indicates if the provided data should fully replace the resource state (as should be done for a PUT request), or if only provided keys should be updated (as should be done for a PATCH request).
validate(data, partial)

Validate new data for the resource.

This method is called to validate data received from a client before it is passed to update_from_dict().

Parameters:
  • data (dict) – data to validate. The data is usually taken directly from JSON send by a client.
  • partial (bool) – indicates if data contains the full resource state (as received in a PUT request), or only partial state (as received in a PATCH request). You can reconstruct the full resource state from partial data by using the complete_partial_data() method.
Raises HTTPException:
 

if all further request processing should be aborted and the exception returned directly.

class rest_toolkit.abc.ViewableResource

Base class for resources using the default GET view.

If a resource class is derived from this class it must implement the to_dict() method. Doing this will automatically enable the default GET view from rest_toolkit.

to_dict()

Generate a (JSON-compatible) dictionary with resource data.

This method is used by the default GET, PATCH and PUT views to generate the data for the response. It is also used by by the PATCH view to complete the (partial) data provided by a client before validation is done (see EditableResource for details).

rest_toolkit.utils

rest_toolkit.utils.merge(base, overlay)

Recursively merge two dictionaries.

This function merges two dictionaries. It is intended to be used to (re)create the full new state of a resource based on its current state and any changes passed in via a PATCH request. The merge rules are:

  • if a key k is present in base but missing in overlay it is untouched.
  • if a key k is present in both base and overlay:
    • and base[k] and overlay[k] are both dictionaries merge is applied recursively,
    • otherwise to value in overlay is used.
  • if a key k is not present in base, but is present in overlay it the value from overlay will be used.
>>> merge({'foo': 'bar'}, {'foo': 'buz'})
{'foo': 'buz'}
>>> merge(['foo': 'bar'}, {'buz': True})
{'foo': 'bar', 'buz': True}
Parameters:
  • base (dict) – Dictionary with default data.
  • overlay (dict) – Dictioanry with data to overlay on top of base.
Return type:

dict

Returns:

A copy of base with data from overlay added.

rest_toolkit.ext.colander

class rest_toolkit.ext.colander.ColanderSchemaValidationMixin

Mix-in class to add colander-based validation to a resource.

This mix-in class provides an implementation for validate() as required by EditableResource which uses colander for validation.

1
2
3
4
5
6
7
class AccountSchema(colander.Schema):
    email = colander.SchemaNode(colander.String())
    password = colander.SchemaNode(colander.String())


class DummyResource(ColanderSchemaValidationMixin):
    schema = AccountSchema
schema

Colander schema class.

rest_toolkit.ext.colander.validate(data, schema)

Validate data against a Colander schema class.

This is a helper function used by ColanderSchemaValidationMixin to validate data against a Colander schema. If validation fails this function will raise a pyramid.httpexceptions.HTTPBadRequest exception describing the validation error.

Raises pyramid.httpexceptions.HTTPBadRequest:
 if validation fails this exception is raised to abort any further processing.

rest_toolkit.ext.jsonschema

class rest_toolkit.ext.jsonschema.JsonSchemaValidationMixin

Mix-in class to add JSON schema validation to a resource.

This mix-in class provides an implementation for validate() as required by EditableResource which uses JSON schemas <http://json-schema.org/>).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Account(EditableResource, JsonSchemaValidationMixin):
    schema = {
            '$schema': 'http://json-schema.org/draft-04/schema',
            'type': 'object',
            'properties': {
                'email': {
                    'type': 'string',
                    'format': 'email',
                 },
                 'password': {
                     'type': 'string',
                     'minLength': 1,
                 },
             },
             'additionalProperties': False,
             'required': ['email', 'password'],
     }

The jsonschema package is used to implement validation. All validation errors reported by jsonschema are returned as a standard error JSON response with HTTP status code 400.

schema

JSON schema.

This attribute must contain a valid JSON schema. This will be used by validate() to validate submitted data.

rest_toolkit.ext.jsonschema.validate(data, schema)

Validate data against a JSON schema.

This is a helper function used by JsonSchemaValidationMixin to validate data against a JSON schema. If validation fails this function will raise a pyramid.httpexceptions.HTTPBadRequest exception describing the validation error.

Raises pyramid.httpexceptions.HTTPBadRequest:
 if validation fails this exception is raised to abort any further processing.

rest_toolkit.ext.sql

class rest_toolkit.ext.sql.SQLResource(request)

Base class for resources based on SQLAlchemy ORM models.

context_query

A SQLAlchemy query which is used to find a SQLAlchemy object.

rest_toolkit.ext.sql.set_sqlalchemy_session_factory(config, sql_session_factory)

Configure the SQLAlchemy session factory.

This function should not be used directly, but as a method if the config object.

1
config.set_sqlalchemy_session_factory(DBSession)

This function must be called if you use SQL resources. If you forget to do this any attempt to access a SQL resource will trigger an assertion exception.

Parameters:sql_session_factory – A factory function to return a SQLAlchemy session. This is generally a scoped_session instance, and commonly called Session or DBSession.
rest_toolkit.ext.sql.includeme(config)

Configure SQLAlchemy integration.

You should not call this function directly, but use pyramid.config.Configurator.include() to initialise the REST toolkit. After you have done this you must call config.set_sqlalchemy_session_factory() to register your SQLALchemy session factory.

1
2
3
4
config = Configurator()
config.include('rest_toolkit')
config.include('rest_toolkit.ext.sql')
config.set_sqlalchemy_session_factory(DBSession)

«  Philosophy   ::   Contents   ::   Comparison with other frameworks  »