graceful.resources package

graceful.resources.base module

class graceful.resources.base.BaseResource

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.

All custom resource classes based on BaseResource accept additional with_context keyword argument:

class MyResource(BaseResource, with_context=True):
    ...

The with_context argument tells if resource modification methods (metods injected with mixins - list/create/update/etc.) should accept the context argument in their signatures. For more details see Dealing with falcon context objects section of documentation. The default value for with_context class keyword argument is False.

Changed in version 0.3.0: Added the with_context keyword argument.

static __new__(*args, **kwargs)

Do some sanity checks before resource instance initialization.

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

Changed in version 0.2.0: The req and resp parameters became optional to ease the implementation of application-level documentation generators.

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

Changed in version 0.2.0: Default OPTIONS responses include Allow header with list of allowed HTTP methods.

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, bulk=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) – set to True if partially complete representation is accepted (e.g. for patching instead of full update). Missing fields in representation will be skiped.
  • bulk (bool) – set to True if request payload represents multiple resources instead of single one.
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(name, bases, namespace, **kwargs)

Metaclass for handling parametrization with parameter objects.

static __new__(mcs, name, bases, namespace, **kwargs)

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 instance so _get_params() method can construct params storage that preserves the same order of parameters as defined in code.

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

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

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)
  • PATCH: create multiple resources from list of representations provided in request body (handled with .create_bulk() method handler.
create_bulk(params, meta, **kwargs)

Create items in bulk by reusing existing .create() handler.

Note

This is default create_bulk implementation that may not be safe to use in production environment depending on your implementation of .create() method handler.

on_patch(req, resp, **kwargs)

Respond on PATCH requests using self.create_bulk() handler.

on_post(req, resp, **kwargs)

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

class graceful.resources.generic.ListResource

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

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

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

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

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

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

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

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.CreateBulkMixin

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

create_bulk(params, meta, **kwargs)

Create multiple resource instances and return their representation.

This is default multiple resource instances creation method. Value returned is the representation of multiple resource instances. 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 the route url template by falcon. This is suggested way for providing resource identifiers.
Returns:

value to be included in response ‘content’ section

on_patch(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 instances and prepare their representation by calling its bulk creation method handler.
  • Set response status code to 201 Created.

Note: this handler does not set Location header by default as it would be valid only for single resource creation.

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.CreateMixin

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

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

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

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

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

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