graceful.resources package

graceful.resources.base module

class graceful.resources.base.BaseResource

Bases: object

Base resouce class with core param and response functionality.

This base class handles resource responses, parameter deserialization, and validation of request included representations if serializer is defined.

allowed_methods()

Return list of allowed HTTP methods on this resource.

This is only for purpose of making resource description.

Returns:list – list of allowed HTTP method names (uppercase)
describe(req=None, resp=None, **kwargs)

Describe API resource using resource introspection.

Additional description on derrived resource class can be added using keyword arguments and calling super().decribe() method call like following:

class SomeResource(BaseResource):
    def describe(req, resp, **kwargs):
        return super().describe(
            req, resp, type='list', **kwargs
         )
Parameters:
  • req (falcon.Request) – request object
  • resp (falcon.Response) – response object
  • kwargs (dict) – dictionary of values created from resource url template
Returns:

dict – dictionary with resource descritpion information

make_body(resp, params, meta, content)

Construct response body in resp object using JSON serialization.

Parameters:
  • resp (falcon.Response) – response object where to include serialized body
  • params (dict) – dictionary of parsed parameters
  • meta (dict) – dictionary of metadata to be included in ‘meta’ section of response
  • content (dict) – dictionary of response content (resource representation) to be included in ‘content’ section of response
Returns:

None

on_options(req, resp, **kwargs)

Respond with JSON formatted resource description on OPTIONS request.

Parameters:
  • req (falcon.Request) – Optional request object. Defaults to None.
  • resp (falcon.Response) – Optional response object. Defaults to None.
  • kwargs (dict) – Dictionary of values created by falcon from resource uri template.
Returns:

None

params

Return dictionary of parameter definition objects.

require_meta_and_content(content_handler, params, **kwargs)

Require ‘meta’ and ‘content’ dictionaries using proper hander.

Parameters:
  • content_handler (callable) – function that accepts params, meta, **kwargs argument and returns dictionary for content response section
  • params (dict) – dictionary of parsed resource parameters
  • kwargs (dict) – dictionary of values created from resource url template
Returns:

tuple (meta, content)

two-tuple with dictionaries of meta and

content response sections

require_params(req)

Require all defined parameters from request query string.

Raises falcon.errors.HTTPMissingParam exception if any of required parameters is missing and falcon.errors.HTTPInvalidParam if any of parameters could not be understood (wrong format).

Parameters:req (falcon.Request) – request object
require_representation(req)

Require raw representation dictionary from falcon request object.

This does not perform any field parsing or validation but only uses allowed content-encoding handler to decode content body.

Note

Currently only JSON is allowed as content type.

Parameters:req (falcon.Request) – request object
Returns:dict – raw dictionary of representation supplied in request body
require_validated(req, partial=False)

Require fully validated internal object dictionary.

Internal object dictionary creation is based on content-decoded representation retrieved from request body. Internal object validation is performed using resource serializer.

Parameters:
  • req (falcon.Request) – request object
  • partial (bool) – self to True if partially complete representation is accepted (e.g. for patching instead of full update). Missing fields in representation will be skiped.
Returns:

dict

dictionary of fields and values representing internal object.

Each value is a result of field.from_representation call.

serializer = None
class graceful.resources.base.MetaResource

Bases: type

Metaclass for handling parametrization with parameter objects.

static __new__(mcs, name, bases, namespace)

Create new class object instance and alter its namespace.

classmethod __prepare__(mcs, name, bases, **kwargs)

Prepare class namespace in a way that ensures order of attributes.

This needs to be an OrderedDict so _get_params() method can construct params storage that preserves the same order of parameters as defined in code.

Note: this is python3 thing and support for ordering of params in descriptions will not be backported to python2 even if this framework will get python2 support.

Parameters:
  • bases – all base classes of created resource class
  • namespace (dict) – namespace as dictionary of attributes

graceful.resources.generic module

class graceful.resources.generic.ListAPI

Bases: graceful.resources.mixins.ListMixin, graceful.resources.base.BaseResource

Generic List API with resource serialization.

Generic resource that uses serializer for resource description, serialization and validation.

Allowed methods:

  • GET: list multiple resource instances representations (handled with .list() method handler)
describe(req=None, resp=None, **kwargs)

Extend default endpoint description with serializer description.

on_get(req, resp, **kwargs)

Respond on GET requests using self.list() handler.

class graceful.resources.generic.ListCreateAPI

Bases: graceful.resources.mixins.CreateMixin, graceful.resources.generic.ListAPI

Generic List/Create API with resource serialization.

Generic resource that uses serializer for resource description, serialization and validation.

Allowed methods:

  • GET: list multiple resource instances representations (handled with .list() method handler)
  • POST: create new resource from representation provided in request body (handled with .create() method handler)
on_post(req, resp, **kwargs)

Respond on POST requests using self.create() handler.

class graceful.resources.generic.ListResource

Bases: graceful.resources.mixins.ListMixin, graceful.resources.base.BaseResource

Basic retrieval of resource instance lists without serialization.

This resource class is intended for endpoints that do not require automatic representation serialization and extensive field descriptions but still gives support for defining parameters as resource class attributes.

Example usage:

class graceful.resources.generic.PaginatedListAPI

Bases: graceful.resources.mixins.PaginatedMixin, graceful.resources.generic.ListAPI

Generic List API with resource serialization and pagination.

Generic resource that uses serializer for resource description, serialization and validation.

Adds simple pagination to list of resources.

Allowed methods:

  • GET: list multiple resource instances representations (handled with .list() method handler)
class graceful.resources.generic.PaginatedListCreateAPI

Bases: graceful.resources.mixins.PaginatedMixin, graceful.resources.generic.ListCreateAPI

Generic List/Create API with resource serialization and pagination.

Generic resource that uses serializer for resource description, serialization and validation.

Adds simple pagination to list of resources.

Allowed methods:

  • GET: list multiple resource instances representations (handled with .list() method handler)
  • POST: create new resource from representation provided in request body (handled with .create() method handler)
class graceful.resources.generic.Resource

Bases: graceful.resources.mixins.RetrieveMixin, graceful.resources.base.BaseResource

Basic retrieval of resource instance lists without serialization.

This resource class is intended for endpoints that do not require automatic representation serialization and extensive field descriptions but still gives support for defining parameters as resource class attributes.

Example usage:

class graceful.resources.generic.RetrieveAPI

Bases: graceful.resources.mixins.RetrieveMixin, graceful.resources.base.BaseResource

Generic Retrieve API with resource serialization.

Generic resource that uses serializer for resource description, serialization and validation.

Allowed methods:

  • GET: retrieve resource representation (handled with .retrieve() method handler)
describe(req=None, resp=None, **kwargs)

Extend default endpoint description with serializer description.

on_get(req, resp, **kwargs)

Respond on GET requests using self.retrieve() handler.

serializer = None
class graceful.resources.generic.RetrieveUpdateAPI

Bases: graceful.resources.mixins.UpdateMixin, graceful.resources.generic.RetrieveAPI

Generic Retrieve/Update API with resource serialization.

Generic resource that uses serializer for resource description, serialization and validation.

Allowed methods:

  • GET: retrieve resource representation handled with .retrieve() method handler
  • PUT: update resource with representation provided in request body (handled with .update() method handler)
on_put(req, resp, **kwargs)

Respond on PUT requests using self.update() handler.

class graceful.resources.generic.RetrieveUpdateDeleteAPI

Bases: graceful.resources.mixins.DeleteMixin, graceful.resources.generic.RetrieveUpdateAPI

Generic Retrieve/Update/Delete API with resource serialization.

Generic resource that uses serializer for resource description, serialization and validation.

Allowed methods:

  • GET: retrieve resource representation (handled with .retrieve() method handler)
  • PUT: update resource with representation provided in request body (handled with .update() method handler)
  • DELETE: delete resource (handled with .delete() method handler)

graceful.resources.mixins module

class graceful.resources.mixins.BaseMixin

Bases: object

Base mixin class.

handle(handler, req, resp, **kwargs)

Handle given resource manipulation flow in consistent manner.

This mixin is intended to be used only as a base class in new flow mixin classes. It ensures that regardless of resource manunipulation semantics (retrieve, get, delete etc.) the flow is always the same:

  1. Decode and validate all request parameters from the query string using self.require_params() method.
  2. Use self.require_meta_and_content() method to construct meta and content dictionaries that will be later used to create serialized response body.
  3. Construct serialized response body using self.body() method.
Parameters:
  • handler (method) – resource manipulation method handler.
  • req (falcon.Request) – request object instance.
  • resp (falcon.Response) – response object instance to be modified.
  • **kwargs – additional keyword arguments retrieved from url template.
Returns:

Content dictionary (preferably resource representation).

class graceful.resources.mixins.CreateMixin

Bases: graceful.resources.mixins.BaseMixin

Add default “creation flow on POST” to any resource class.

create(params, meta, **kwargs)

Create new resource instance and return its representation.

This is default resource instance creation method. Value returned is the representation of single resource instance. It will be included in the ‘content’ section of response body.

Parameters:
  • params (dict) – dictionary of parsed parameters accordingly to definitions provided as resource class atributes.
  • meta (dict) – dictionary of meta parameters anything added to this dict will will be later included in response ‘meta’ section. This can already prepopulated by method that calls this handler.
  • kwargs (dict) – dictionary of values retrieved from route url template by falcon. This is suggested way for providing resource identifiers.
Returns:

value to be included in response ‘content’ section

get_object_location(obj)

Return location URI associated with given resource representation.

This handler is optional. Returned URI will be included as the value of Location header on POST responses.

on_post(req, resp, handler=None, **kwargs)

Respond on POST HTTP request assuming resource creation flow.

This request handler assumes that POST requests are associated with resource creation. Thus default flow for such requests is:

  • Create new resource instance and prepare its representation by calling its creation method handler.
  • Try to retrieve URI of newly created object using self.get_object_location(). If it succeeds use that URI as the value of Location header in response object instance.
  • Set response status code to 201 Created.
Parameters:
  • req (falcon.Request) – request object instance.
  • resp (falcon.Response) – response object instance to be modified
  • handler (method) – creation method handler to be called. Defaults to self.create.
  • **kwargs – additional keyword arguments retrieved from url template.
class graceful.resources.mixins.DeleteMixin

Bases: graceful.resources.mixins.BaseMixin

Add default “delete flow on DELETE” to any resource class.

delete(params, meta, **kwargs)

Delete existing resource instance.

Parameters:
  • params (dict) – dictionary of parsed parameters accordingly to definitions provided as resource class atributes.
  • meta (dict) – dictionary of meta parameters anything added to this dict will will be later included in response ‘meta’ section. This can already prepopulated by method that calls this handler.
  • **kwargs – dictionary of values retrieved from route url template by falcon. This is suggested way for providing resource identifiers.
Returns:

value to be included in response ‘content’ section

on_delete(req, resp, handler=None, **kwargs)

Respond on DELETE HTTP request assuming resource deletion flow.

This request handler assumes that DELETE requests are associated with resource deletion. Thus default flow for such requests is:

  • Delete existing resource instance.
  • Set response status code to 202 Accepted.
Parameters:
  • req (falcon.Request) – request object instance.
  • resp (falcon.Response) – response object instance to be modified
  • handler (method) – deletion method handler to be called. Defaults to self.delete.
  • **kwargs – additional keyword arguments retrieved from url template.
class graceful.resources.mixins.ListMixin

Bases: graceful.resources.mixins.BaseMixin

Add default “list flow on GET” to any resource class.

list(params, meta, **kwargs)

List existing resource instances and return their representations.

Value returned by this handler will be included in response ‘content’ section.

Parameters:
  • params (dict) – dictionary of parsed parameters accordingly to definitions provided as resource class atributes.
  • meta (dict) – dictionary of meta parameters anything added to this dict will will be later included in response ‘meta’ section. This can already prepopulated by method that calls this handler.
  • **kwargs – dictionary of values retrieved from route url template by falcon. This is suggested way for providing resource identifiers.
Returns:

value to be included in response ‘content’ section

on_get(req, resp, handler=None, **kwargs)

Respond on GET HTTP request assuming resource list retrieval flow.

This request handler assumes that GET requests are associated with resource list retrieval. Thus default flow for such requests is:

  • Retrieve list of existing resource instances and prepare their representations by calling list retrieval method handler.
Parameters:
  • req (falcon.Request) – request object instance.
  • resp (falcon.Response) – response object instance to be modified
  • handler (method) – list method handler to be called. Defaults to self.list.
  • **kwargs – additional keyword arguments retrieved from url template.
class graceful.resources.mixins.PaginatedMixin

Bases: graceful.resources.base.BaseResource

Add simple pagination capabilities to resource.

This class provides two additional parameters with some default descriptions and add_pagination_meta method that can update meta with more useful pagination information.

Example usage:

from graceful.resources.mixins import PaginatedMixin
from graceful.resources.generic import ListResource

class SomeResource(PaginatedMixin, ListResource):

    def list(self, params, meta):
        # params has now 'page' and 'page_size' params that
        # can be used for offset&limit-like operations
        self.add_pagination_meta(params, meta)

        # ...
add_pagination_meta(params, meta)

Extend default meta dictionary value with pagination hints.

Note

This method handler attaches values to meta dictionary without changing it’s reference. This means that you should never replace meta dictionary with any other dict instance but simply modify its content.

Parameters:
  • params (dict) – dictionary of decoded parameter values
  • meta (dict) – dictionary of meta values attached to response
class graceful.resources.mixins.RetrieveMixin

Bases: graceful.resources.mixins.BaseMixin

Add default “retrieve flow on GET” to any resource class.

on_get(req, resp, handler=None, **kwargs)

Respond on GET HTTP request assuming resource retrieval flow.

This request handler assumes that GET requests are associated with single resource instance retrieval. Thus default flow for such requests is:

  • Retrieve single resource instance of prepare its representation by calling retrieve method handler.
Parameters:
  • req (falcon.Request) – request object instance.
  • resp (falcon.Response) – response object instance to be modified
  • handler (method) – list method handler to be called. Defaults to self.list.
  • **kwargs – additional keyword arguments retrieved from url template.
retrieve(params, meta, **kwargs)

Retrieve existing resource instance and return its representation.

Value returned by this handler will be included in response ‘content’ section.

Parameters:
  • params (dict) – dictionary of parsed parameters accordingly to definitions provided as resource class atributes.
  • meta (dict) – dictionary of meta parameters anything added to this dict will will be later included in response ‘meta’ section. This can already prepopulated by method that calls this handler.
  • **kwargs – dictionary of values retrieved from route url template by falcon. This is suggested way for providing resource identifiers.
Returns:

value to be included in response ‘content’ section

class graceful.resources.mixins.UpdateMixin

Bases: graceful.resources.mixins.BaseMixin

Add default “update flow on PUT” to any resource class.

on_put(req, resp, handler=None, **kwargs)

Respond on PUT HTTP request assuming resource update flow.

This request handler assumes that PUT requests are associated with resource update/modification. Thus default flow for such requests is:

  • Modify existing resource instance and prepare its representation by calling its update method handler.
  • Set response status code to 202 Accepted.
Parameters:
  • req (falcon.Request) – request object instance.
  • resp (falcon.Response) – response object instance to be modified
  • handler (method) – update method handler to be called. Defaults to self.update.
  • **kwargs – additional keyword arguments retrieved from url template.
update(params, meta, **kwargs)

Update existing resource instance and return its representation.

Value returned by this handler will be included in response ‘content’ section.

Parameters:
  • params (dict) – dictionary of parsed parameters accordingly to definitions provided as resource class atributes.
  • meta (dict) – dictionary of meta parameters anything added to this dict will will be later included in response ‘meta’ section. This can already prepopulated by method that calls this handler.
  • **kwargs – dictionary of values retrieved from route url template by falcon. This is suggested way for providing resource identifiers.
Returns:

value to be included in response ‘content’ section