API Docs

REST API for invenio-records.

class invenio_records_rest.ext.InvenioRecordsREST(app=None)[source]

Invenio-Records-REST extension.

init_app(app)[source]

Flask application initialization.

init_config(app)[source]

Initialize configuration.

Configuration

Invenio-Records-REST configuration.

invenio_records_rest.config.RECORDS_REST_DEFAULT_CREATE_PERMISSION_FACTORY(*args, **kwargs)

Default create permission factory: reject any request.

invenio_records_rest.config.RECORDS_REST_DEFAULT_DELETE_PERMISSION_FACTORY(*args, **kwargs)

Default delete permission factory: reject any request.

invenio_records_rest.config.RECORDS_REST_DEFAULT_LOADERS = {'application/json-patch+json': <function <lambda>>, 'application/json': <function <lambda>>}

Default data loaders per request mime type.

This option can be overritten in each REST endpoint as follows:

RECORDS_REST_ENDPOINTS = {
    'recid': {
        ...
        'record_loaders': {
            'aplication/json': 'mypackage.utils:myloader',
        },
        ...
    }
}
invenio_records_rest.config.RECORDS_REST_DEFAULT_READ_PERMISSION_FACTORY(record, *args, **kwargs)

Default read permission factory: check if the record exists.

invenio_records_rest.config.RECORDS_REST_DEFAULT_SORT = {'records': {'noquery': 'mostrecent', 'query': 'bestmatch'}}

Default sort option per index with/without query string.

The structure of the dictionary is as follows:

RECORDS_REST_DEFAULT_SORT = {
    '<index or index alias>': {
        'query': '<default-sort-if-a-query-is-passed-from-url>',
        'noquery': '<default-sort-if-no-query-in-passed-from-url>',
    }
}
invenio_records_rest.config.RECORDS_REST_DEFAULT_UPDATE_PERMISSION_FACTORY(*args, **kwargs)

Default update permission factory: reject any request.

invenio_records_rest.config.RECORDS_REST_ELASTICSEARCH_ERROR_HANDLERS = {'query_parsing_exception': 'invenio_records_rest.views:elasticsearch_query_parsing_exception_handler'}

Handlers for ElasticSearch error codes.

invenio_records_rest.config.RECORDS_REST_ENDPOINTS = {'recid': {'list_route': '/records/', 'default_media_type': 'application/json', 'max_result_window': 10000, 'item_route': '/records/<pid(recid):pid_value>', 'search_index': None, 'pid_type': 'recid', 'search_class': <class 'invenio_search.api.RecordsSearch'>, 'search_type': None, 'search_serializers': {'application/json': 'invenio_records_rest.serializers:json_v1_search'}, 'pid_fetcher': 'recid', 'record_serializers': {'application/json': 'invenio_records_rest.serializers:json_v1_response'}, 'pid_minter': 'recid'}}

Default REST endpoints loaded.

This option can be overwritten to describe the endpoints of different record types. Each endpoint is in charge of managing all its CRUD operations (GET, POST, PUT, DELETE, ...).

The structure of the dictionary is as follows:

from flask import abort
from flask_security import current_user
from invenio_records_rest.query import es_search_factory


def search_factory(*args, **kwargs):
    if not current_user.is_authenticated:
        abort(401)
    return es_search_factory(*args, **kwargs)


def permission_check_factory():
    def check_title(record, *args, **kwargs):
        def can(self):
            if record['title'] == 'Hello World':
                return True
        return type('Check', (), {'can': can})()


RECORDS_REST_ENDPOINTS = {
    'endpoint-prefix': {
        'create_permission_factory_imp': permission_check_factory(),
        'default_endpoint_prefix': True,
        'default_media_type': 'application/json',
        'delete_permission_factory_imp': permission_check_factory(),
        'item_route': ''/recods/<pid(record-pid-type):pid_value>'',
        'links_factory_imp': ('invenio_records_rest.links:'
                              'default_links_factory'),
        'list_route': '/records/',
        'max_result_window': 10000,
        'pid_fetcher': '<registered-pid-fetcher>',
        'pid_minter': '<registered-minter-name>',
        'pid_type': '<record-pid-type>',
        'read_permission_factory_imp': permission_check_factory(),
        'record_class': 'mypackage.api:MyRecord',
        'record_loaders': {
            'application/json': 'mypackage.loaders:json_loader'
        },
        'record_serializers': {
            'application/json': 'mypackage.utils:my_json_serializer'
        },
        'search_class': 'mypackage.utils:mysearchclass',
        'search_factory_imp': search_factory(),
        'search_index': 'elasticsearch-index-name',
        'search_serializers': {
            'application/json': 'mypackage.utils:my_json_search_serializer'
        },
        'search_type': 'elasticsearch-doc-type',
        'suggesters': {
            'my_url_param_to_complete': {
                'completion': {
                    'field': 'suggest_byyear_elasticsearch_field',
                    'size': 10,
                    'context': 'year'
                }
            },
        },
        'update_permission_factory_imp': permission_check_factory(),
        'use_options_view': True,
    },
}
Parameters:
  • create_permission_factory_imp – Import path to factory that create permission object for a given record.
  • default_endpoint_prefix – declare the current endpoint as the default when building endpoints for the defined pid_type. By default the default prefix is defined to be the value of pid_type.
  • default_media_type – Default media type for both records and search.
  • delete_permission_factory_imp – Import path to factory that creates a delete permission object for a given record.
  • item_route – URL rule for a single record.
  • links_factory_imp – Factory for record links generation.
  • list_route – Base URL for the records endpoint.
  • max_result_window – Maximum total number of records retrieved from a query.
  • pid_type – It specifies the record pid type. Required. You can generate an URL to list all records of the given pid_type by calling url_for('invenio_records_rest.{0}_list'.format( current_records_rest.default_endpoint_prefixes[pid_type])).
  • pid_fetcher – It identifies the registered fetcher name. Required.
  • pid_minter – It identifies the registered minter name. Required.
  • read_permission_factory_imp – Import path to factory that creates a read permission object for a given record.
  • record_class – A record API class or importable string.
  • record_loaders – It contains the list of record deserializers for supperted formats.
  • record_serializers – It contains the list of record serializers for supported formats.
  • search_class – Import path or class object for the object in charge of execute the search queries. The default search class is invenio_search.api.RecordsSearch. For more information about resource loading, see the Search <http://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html> of the ElasticSearch DSL library.
  • search_factory_imp – Factory to parse quieries.
  • search_index – Name of the search index used when searching records.
  • search_serializers – It contains the list of records serializers for all supported format. This configuration differ from the previous because in this case it handle a list of records resulted by a search query instead of a single record.
  • search_type – Name of the search type used when searching records.
  • suggesters

    Suggester fields configuration. Any element of the dictionary represents a suggestion field. The key of the dictionary element is used to identify the url query parameter. The field parameter identifies the suggester field name in your elasticsearch schema. To have more information about suggestion configuration, you can read suggesters section on ElasticSearch documentation.

    Note

    Only completion suggessters are supported.

  • update_permission_factory_imp – Import path to factory that creates a update permission object for a given record.
  • use_options_view – Determines if a special option view should be installed.
invenio_records_rest.config.RECORDS_REST_FACETS = {'records': {'post_filters': {'type': <function inner>}, 'aggs': {'type': {'terms': {'field': 'type'}}}}}

Facets per index for the default facets factory.

The structure of the dictionary is as follows:

RECORDS_REST_FACETS = {
    '<index or index alias>': {
        'aggs': {
            '<key>': <aggregation definition>,
            ...
        }
        'filters': {
            '<key>': <filter func>,
            ...
        }
        'post_filters': {
            '<key>': <filter func>,
            ...
        }
    }
}
invenio_records_rest.config.RECORDS_REST_SORT_OPTIONS = {'records': {'bestmatch': {'fields': ['_score'], 'default_order': 'desc', 'order': 1, 'title': 'Best match'}, 'mostrecent': {'fields': ['created_date'], 'default_order': 'desc', 'order': 2, 'title': 'Most recent'}}}

Sort options for default sorter factory.

The structure of the dictionary is as follows:

RECORDS_REST_SORT_OPTIONS = {
    '<index or index alias>': {
        '<sort-field-name>': {
            'fields': ['<search_field>', '<search_field>', ...],
            'title': '<title displayed to end user in search-ui>',
            'default_order': '<default sort order in search-ui>',
        }
    }
}

Each search field can be either:

  • A string of the form '<field name>' (ascending) or '-<field name>' (descending).
  • A dictionary with Elasicsearch sorting syntax (e.g. {'price' : {'order' : 'asc', 'mode' : 'avg'}}).
  • A callable taking one boolean parameter (True for ascending and False for descending) and returning a dictionary like above. This is useful if you need to extract extra sorting parameters (e.g. for geo location searches).

Facets factory for REST API.

invenio_records_rest.facets.default_facets_factory(search, index)[source]

Add a default facets to query.

Parameters:
  • search – Basic search object.
  • index – Index name.
Returns:

A tuple containing the new search object and a dictionary with all fields and values used.

invenio_records_rest.facets.range_filter(field, start_date_math=None, end_date_math=None, **kwargs)[source]

Create a range filter.

Parameters:
  • field – Field name.
  • start_date_math – Starting date.
  • end_date_math – Ending date.
  • kwargs – Addition arguments passed to the Range query.
Returns:

Function that returns the Range query.

invenio_records_rest.facets.terms_filter(field)[source]

Create a term filter.

Parameters:field – Field name.
Returns:Function that returns the Terms query.

Sorter factory for REST API.

The default sorter factory allows you to define possible sort options in the RECORDS_REST_SORT_OPTIONS configuration variable. The sort options are defined per index alias (e.g. records). If more fine grained control is needed a custom sorter factory can be provided to Records-REST instead.

See Elasticsearch Reference Manual for full details of sorting capabilities: https://www.elastic.co/guide/en/elasticsearch/reference/2.x/search-request-sort.html

invenio_records_rest.sorter.default_sorter_factory(search, index)[source]

Default sort query factory.

Parameters:
  • query – Search query.
  • index – Index to search in.
Returns:

Tuple of (query, URL arguments).

invenio_records_rest.sorter.eval_field(field, asc)[source]

Evaluate a field for sorting purpose.

Parameters:
  • field – Field definition (string, dict or callable).
  • ascTrue if order is ascending, False if descending.
Returns:

Dictionary with the sort field query.

invenio_records_rest.sorter.geolocation_sort(field_name, argument, unit, mode=None, distance_type=None)[source]

Sort field factory for geo-location based sorting.

Parameters:
  • argument – Name of URL query string field to parse pin location from. Multiple locations can be provided. Each location can be either a string “latitude,longitude” or a geohash.
  • unit – Distance unit (e.g. km).
  • mode – Sort mode (avg, min, max).
  • distance_type – Distance calculation mode.
Returns:

Function that returns geolocation sort field.

invenio_records_rest.sorter.parse_sort_field(field_value)[source]

Parse a URL field.

Parameters:field_value – Field value (e.g. ‘key’ or ‘-key’).
Returns:Tuple of (field, ascending) as string and boolean.
invenio_records_rest.sorter.reverse_order(order_value)[source]

Reserve ordering of order value (asc or desc).

Parameters:order_value – Either the string asc or desc.
Returns:Reverse sort order of order value.

Links for record serialization.

Factory for record links generation.

Parameters:pid – A Persistent Identifier instance.
Returns:Dictionary containing a list of useful links for the record.

Query factories for REST API.

invenio_records_rest.query.default_search_factory(self, search, query_parser=None)[source]

Parse query using Invenio-Query-Parser.

Parameters:
  • self – REST view.
  • search – Elastic search DSL search instance.
Returns:

Tuple with search instance and URL arguments.

Implementention of various utility functions.

class invenio_records_rest.utils.LazyPIDValue(resolver, value)[source]

Lazy resolver for PID value.

data[source]

Resolve PID value and return tuple with PID and record.

Returns:A tuple with the PID and the record resolved.
class invenio_records_rest.utils.PIDConverter(url_map, pid_type, getter=None, record_class=None)[source]

Resolve PID value.

to_python(value)[source]

Resolve PID value.

class invenio_records_rest.utils.PIDPathConverter(url_map, pid_type, getter=None, record_class=None)[source]

Resolve PID path value.

invenio_records_rest.utils.allow_all(*args, **kwargs)[source]

Return permission that always allow an access.

Returns:A object instance with a can() method.
invenio_records_rest.utils.build_default_endpoint_prefixes(records_rest_endpoints)[source]

Build the default_endpoint_prefixes map.

invenio_records_rest.utils.check_elasticsearch(record, *args, **kwargs)[source]

Return permission that check if the record exists in ES index.

Params record:A record object.
Returns:A object instance with a can() method.
invenio_records_rest.utils.deny_all(*args, **kwargs)[source]

Return permission that always deny an access.

Returns:A object instance with a can() method.
invenio_records_rest.utils.load_or_import_from_config(key, app=None, default=None)[source]

Load or import value from config.

Returns:The loaded value.
invenio_records_rest.utils.obj_or_import_string(value, default=None)[source]

Import string or return object.

Params value:Import path or class object to instantiate.
Params default:Default object to return if the import fails.
Returns:The imported object.

Errors

Search errors.

exception invenio_records_rest.errors.InvalidDataRESTError(errors=None, **kwargs)[source]

Invalid request body.

exception invenio_records_rest.errors.InvalidQueryRESTError(errors=None, **kwargs)[source]

Invalid query syntax.

exception invenio_records_rest.errors.MaxResultWindowRESTError(errors=None, **kwargs)[source]

Maximum number of results have been reached.

exception invenio_records_rest.errors.PIDDeletedRESTError(errors=None, **kwargs)[source]

Deleted PID.

exception invenio_records_rest.errors.PIDDoesNotExistRESTError(errors=None, **kwargs)[source]

Non-existent PID.

exception invenio_records_rest.errors.PIDMissingObjectRESTError(pid, **kwargs)[source]

PID missing object.

exception invenio_records_rest.errors.PIDRedirectedRESTError(pid_type=None, **kwargs)[source]

Invalid redirect for destination.

exception invenio_records_rest.errors.PIDResolveRESTError(pid=None, **kwargs)[source]

Invalid PID.

exception invenio_records_rest.errors.PIDUnregisteredRESTError(errors=None, **kwargs)[source]

Unregistered PID.

exception invenio_records_rest.errors.PatchJSONFailureRESTError(errors=None, **kwargs)[source]

Failed to patch JSON.

exception invenio_records_rest.errors.StyleNotFoundRESTError(style=None, **kwargs)[source]

No such style.

exception invenio_records_rest.errors.SuggestMissingContextRESTError(ctx_field=None, **kwargs)[source]

Missing a context value when getting record suggestions.

exception invenio_records_rest.errors.SuggestNoCompletionsRESTError(options=None, **kwargs)[source]

No completion requested when getting record suggestions.

exception invenio_records_rest.errors.UnsupportedMediaRESTError(content_type=None, **kwargs)[source]

Creating record with unsupported media type.

Views

REST API resources.

invenio_records_rest.views.create_url_rules(endpoint, list_route=None, item_route=None, pid_type=None, pid_minter=None, pid_fetcher=None, read_permission_factory_imp=None, create_permission_factory_imp=None, update_permission_factory_imp=None, delete_permission_factory_imp=None, record_class=None, record_serializers=None, record_loaders=None, search_class=None, search_serializers=None, search_index=None, search_type=None, default_media_type=None, max_result_window=None, use_options_view=True, search_factory_imp=None, links_factory_imp=None, suggesters=None, default_endpoint_prefix=None)[source]

Create Werkzeug URL rules.

Parameters:
  • endpoint – Name of endpoint.
  • list_route – Record listing URL route. Required.
  • item_route – Record URL route (must include <pid_value> pattern). Required.
  • pid_type – Persistent identifier type for endpoint. Required.
  • pid_minter – It identifies the registered minter name.
  • pid_fetcher – It identifies the registered fetcher name.
  • read_permission_factory_imp – Import path to factory that creates a read permission object for a given record.
  • create_permission_factory_imp – Import path to factory that creates a create permission object for a given record.
  • update_permission_factory_imp – Import path to factory that creates a update permission object for a given record.
  • delete_permission_factory_imp – Import path to factory that creates a delete permission object for a given record.
  • default_endpoint_prefix – ignored.
  • record_class – A record API class or importable string.
  • record_serializers – Serializers used for records.
  • record_loaders – It contains the list of record deserializers for supperted formats.
  • search_class – Import path or class object for the object in charge of execute the search queries. The default search class is invenio_search.api.RecordsSearch. For more information about resource loading, see the Search of ElasticSearch DSL library.
  • search_serializers – Serializers used for search results.
  • search_index – Name of the search index used when searching records.
  • search_type – Name of the search type used when searching records.
  • default_media_type – Default media type for both records and search.
  • max_result_window – Maximum number of results that Elasticsearch can provide for the given search index without use of scroll. This value should correspond to Elasticsearch index.max_result_window value for the index.
  • use_options_view – Determines if a special option view should be installed.
  • search_factory_imp – Factory to parse quieries.
  • links_factory_imp – Factory for record links generation.
  • suggesters – Suggester fields configuration.
Returns:

a list of dictionaries with can each be passed as keywords arguments to Blueprint.add_url_rule.

Integrations

Support for Memento response.

class invenio_records_rest.memento.MementoRecord(data, model=None)[source]

Implement basic Memento protocol.

The original resource acts as its own TimeGate without distict Memento URI (see section 4.1.3).

classmethod get_record(*args, **kwargs)[source]

Return record object and enhance response.

invenio_records_rest.memento.get_memento(record, accept_datetime)[source]

Return revision of the record for given datetime.