aiida.restapi.common package


Constants used in rest api

aiida.restapi.common.config.APP_CONFIG = {'DEBUG': False, 'PROPAGATE_EXCEPTIONS': True}

JSON serialization config. Leave this dictionary empty if default Flask serializer is desired.

Here is a list a all supported fields. If a field is not present in the dictionary its value is assumed to be ‘default’.

DATETIME_FORMAT: allowed values are ‘asinput’ and ‘default’.

aiida.restapi.common.config.MAX_TREE_DEPTH = 5

Aiida profile used by the REST api when no profile is specified (ex. by –aiida-profile flag). This has to be one of the profiles registered in .aiida/config.json

In case you want to use the default stored in .aiida/config.json, set this varibale to “default”

aiida.restapi.common.config.PREFIX = '/api/v3'

Flask app configs.

DEBUG: True/False. enables debug mode N.B. !!!For production run use ALWAYS False!!!

PROPAGATE_EXCEPTIONS: True/False serve REST exceptions to the client (and not a generic 500: Internal Server Error exception)

aiida.restapi.common.config.SERIALIZER_CONFIG = {'datetime_format': 'default'}

Caching configuration

memcached: backend caching system

This file contains the exceptions that are raised by the RESTapi at the highest level, namely that of the interaction with the client. Their specificity resides into the fact that they return a message that is embedded into the HTTP response.


…/api/v1/nodes/ … (TODO compete this with an actual example)

Other errors arising at deeper level, e.g. those raised by the QueryBuilder or internal errors, are not embedded into the HTTP response.

exception aiida.restapi.common.exceptions.RestFeatureNotAvailable[source]

Bases: aiida.common.exceptions.FeatureNotAvailable

__module__ = 'aiida.restapi.common.exceptions'
exception aiida.restapi.common.exceptions.RestInputValidationError[source]

Bases: aiida.common.exceptions.InputValidationError

document with an example

__module__ = 'aiida.restapi.common.exceptions'
exception aiida.restapi.common.exceptions.RestValidationError[source]

Bases: aiida.common.exceptions.ValidationError

document with an example

__module__ = 'aiida.restapi.common.exceptions'

Util methods

class aiida.restapi.common.utils.CustomJSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False)[source]

Bases: flask.json.JSONEncoder

Custom json encoder for serialization. This has to be provided to the Flask app in order to replace the default encoder.

__module__ = 'aiida.restapi.common.utils'

Override default method from JSONEncoder to change serializer :param o: Object e.g. dict, list that will be serialized :return: serialized object

class aiida.restapi.common.utils.DatetimePrecision(dtobj, precision)[source]

Bases: object

A simple class which stores a datetime object with its precision. No internal check is done (cause itis not possible).

precision: 1 (only full date)

2 (date plus hour) 3 (date + hour + minute) 4 (dare + hour + minute +second)

__dict__ = mappingproxy({'__module__': 'aiida.restapi.common.utils', '__doc__': '\n A simple class which stores a datetime object with its precision. No\n internal check is done (cause itis not possible).\n\n precision: 1 (only full date)\n 2 (date plus hour)\n 3 (date + hour + minute)\n 4 (dare + hour + minute +second)\n ', '__init__': <function DatetimePrecision.__init__>, '__dict__': <attribute '__dict__' of 'DatetimePrecision' objects>, '__weakref__': <attribute '__weakref__' of 'DatetimePrecision' objects>})
__init__(dtobj, precision)[source]

Constructor to check valid datetime object and precision

__module__ = 'aiida.restapi.common.utils'

list of weak references to the object (if defined)

class aiida.restapi.common.utils.Utils(**kwargs)[source]

Bases: object

A class that gathers all the utility functions for parsing URI, validating request, pass it to the translator, and building HTTP response

An istance of Utils has to be included in the api class so that the configuration parameters used to build the api are automatically accessible by the methods of Utils without the need to import them from the file.

__dict__ = mappingproxy({'__module__': 'aiida.restapi.common.utils', '__doc__': '\n A class that gathers all the utility functions for parsing URI,\n validating request, pass it to the translator, and building HTTP response\n\n An istance of Utils has to be included in the api class so that the\n configuration parameters used to build the api are automatically\n accessible by the methods of Utils without the need to import them from\n the file.\n\n ', 'op_conv_map': {'=': '==', '!=': '!==', '=in=': 'in', '=notin=': '!in', '>': '>', '<': '<', '>=': '>=', '<=': '<=', '=like=': 'like', '=ilike=': 'ilike'}, '__init__': <function Utils.__init__>, 'strip_api_prefix': <function Utils.strip_api_prefix>, 'split_path': <staticmethod object>, 'parse_path': <function Utils.parse_path>, 'validate_request': <function Utils.validate_request>, 'paginate': <function Utils.paginate>, 'build_headers': <function Utils.build_headers>, 'build_response': <staticmethod object>, 'build_datetime_filter': <staticmethod object>, 'build_translator_parameters': <function Utils.build_translator_parameters>, 'parse_query_string': <function Utils.parse_query_string>, '__dict__': <attribute '__dict__' of 'Utils' objects>, '__weakref__': <attribute '__weakref__' of 'Utils' objects>})

Sets internally the configuration parameters

__module__ = 'aiida.restapi.common.utils'

list of weak references to the object (if defined)

static build_datetime_filter(dtobj)[source]

This function constructs a filter for a datetime object to be in a certain datetime interval according to the precision.

The interval is [reference_datetime, reference_datetime + delta_time], where delta_time is a function fo the required precision.

This function should be used to replace a datetime filter based on the equality operator that is inehrently “picky” because it implies matching two datetime objects down to the microsecond or something, by a “tolerant” operator which checks whether the datetime is in an interval.


a suitable entry of the filter dictionary

build_headers(rel_pages=None, url=None, total_count=None)[source]

Construct the header dictionary for an HTTP response. It includes related pages, total count of results (before pagination).

  • rel_pages – a dictionary defining related pages (first, prev, next, last)

  • url – (string) the full url, i.e. the url that the client uses to get Rest resources

static build_response(status=200, headers=None, data=None)[source]

Build the response

  • status – status of the response, e.g. 200=OK, 400=bad request

  • headers – dictionary for additional header k,v pairs, e.g. X-total-count=<number of rows resulting from query>

  • data – a dictionary with the data returned by the Resource


a Flask response object


Takes a list of elements resulting from the parsing the query_string and elaborates them in order to provide translator-compliant instructions


field_list – a (nested) list of elements resulting from parsing the query_string


the filters in the

op_conv_map = {'!=': '!==', '<': '<', '<=': '<=', '=': '==', '=ilike=': 'ilike', '=in=': 'in', '=like=': 'like', '=notin=': '!in', '>': '>', '>=': '>='}
paginate(page, perpage, total_count)[source]

Calculates limit and offset for the reults of a query, given the page and the number of restuls per page. Moreover, calculates the last available page and raises an exception if the required page exceeds that limit. If number of rows==0, only page 1 exists :param page: integer number of the page that has to be viewed :param perpage: integer defining how many results a page contains :param total_count: the total number of rows retrieved by the query :return: integers: limit, offset, rel_pages

parse_path(path_string, parse_pk_uuid=None)[source]

Takes the path and parse it checking its validity. Does not parse “io”, “content” fields. I do not check the validity of the path, since I assume that this is done by the Flask routing methods.

  • path_string – the path string

  • parse_id_uuid – if ‘pk’ (‘uuid’) expects an integer (uuid starting pattern)


resource_type (string) page (integer) node_id (string: uuid starting pattern, int: pk) query_type (string))


Function that parse the querystring, extracting infos for limit, offset, ordering, filters, attribute and extra projections. :param query_string (as obtained from request.query_string) :return: parsed values for the querykeys

static split_path(path)[source]

path – entire path contained in flask request


list of each element separated by ‘/’


Removes the PREFIX from an URL path. PREFIX must be defined in the file:

PREFIX = "/api/v2"
path = "/api/v2/calculations/page/2"
strip_api_prefix(path) ==> "/calculations/page/2"

path – the URL path string


the same URL without the prefix

validate_request(limit=None, offset=None, perpage=None, page=None, query_type=None, is_querystring_defined=False)[source]

Performs various checks on the consistency of the request. Add here all the checks that you want to do, except validity of the page number that is done in paginate(). Future additional checks must be added here


List available routes