API Docs

Flask extension for the Invenio-Records-REST.

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

Invenio-Records-REST extension.

Extension initialization.

init_app(app)[source]

Flask application initialization.

init_config(app)[source]

Initialize configuration.

Facets

Facets and factories for result filtering and aggregation.

See invenio_records_rest.config.RECORDS_REST_FACETS for more information on how to specify aggregations and filters.

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

Add a default facets to query.

It’s possible to select facets which should be added to query by passing their name in facets parameter.

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

Sorter factories for REST API.

The default sorter factory allows you to define possible sort options in the invenio_records_rest.config.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.4/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.

Query

Query factories for REST API.

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

Parse query using elasticsearch DSL query.

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

Tuple with search instance and URL arguments.

invenio_records_rest.query.es_search_factory(self, search, query_parser=None)

Parse query using elasticsearch DSL query.

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

Tuple with search instance and URL arguments.

Serializers

Record serialization.

invenio_records_rest.serializers.json_v1 = <invenio_records_rest.serializers.json.JSONSerializer object>

JSON v1 serializer.

invenio_records_rest.serializers.json_v1_response(pid, record, code=200, headers=None, links_factory=None)

JSON response builder that uses the JSON v1 serializer.

JSON search response builder that uses the JSON v1 serializer.

Mixins

Mixin helper class for preprocessing records and search results.

class invenio_records_rest.serializers.base.PreprocessorMixin(replace_refs=False, **kwargs)[source]

Base class for serializers.

Constructor.

preprocess_record(pid, record, links_factory=None, **kwargs)[source]

Prepare a record and persistent identifier for serialization.

static preprocess_search_hit(pid, record_hit, links_factory=None, **kwargs)[source]

Prepare a record hit from Elasticsearch for serialization.

class invenio_records_rest.serializers.base.PreprocessorMixinInterface[source]

Mixin preprocessing records during serialization.

This class should be mixed with a TransformerMixinInteface subclass and a SerializerMixinInterface subclass.

This class builds a dictionary which is then transformed and serialized.

preprocess_record(pid, record, links_factory=None, **kwargs)[source]

Prepare a record and persistent identifier for serialization.

Parameters:
  • pid – Persistent identifier instance.
  • record – Record instance.
  • links_factory – Factory function for record links.
static preprocess_search_hit(pid, record_hit, links_factory=None, **kwargs)[source]

Prepare a record hit from Elasticsearch for serialization.

Parameters:
  • pid – Persistent identifier instance.
  • record_hit – Record metadata retrieved via search.
  • links_factory – Factory function for record links.
class invenio_records_rest.serializers.base.SerializerMixinInterface[source]

Mixin serializing records.

A record serializer should inherit subclasses of - SerializerMixinInterface - TransformerMixinInterface - PreprocessorMixinInterface

This class forwards its input to the transformer mixin and serializes its result.

serialize(pid, record, links_factory=None, **kwargs)[source]

Serialize a single record and persistent identifier.

This method should delegate the record transformation to the transformer mixin’s transform_record method.

Parameters:
  • pid – Persistent identifier instance.
  • record – Record instance.
  • links_factory – Factory function for record links.
serialize_oaipmh(pid, record)[source]

Serialize a single record for OAI-PMH.

Parameters:
Returns:

The object serialized.

Serialize a search result.

This method should delegate each record search hit transformation to the transformer mixin’s transform_search_hit method.

Parameters:
  • pid_fetcher – Persistent identifier fetcher.
  • search_result – Elasticsearch search result.
  • links – Dictionary of links to add to response.
  • item_links_factory – Factory function for record links.
class invenio_records_rest.serializers.base.TransformerMixinInterface[source]

Mixin transforming records during serialization.

This class should be mixed with a PreprocessorMixinInterface subclass and a SerializerMixinInterface subclass.

This class transforms the dictionary returned by the preprocessor.

transform_record(pid, record, links_factory=None, **kwargs)[source]

Transform record into an intermediate representation.

This method should delegate the record preprocessing to the preprocessor mixin’s preprocess_record method.

Parameters:
  • pid – Persistent identifier instance.
  • record – Record instance.
  • links_factory – Factory function for record links.
transform_search_hit(pid, record_hit, links_factory=None, **kwargs)[source]

Transform search result hit into an intermediate representation.

This method should delegate the record preprocessing to the preprocessor mixin’s preprocess_search_hit method.

Parameters:
  • pid – Persistent identifier instance.
  • pid – Persistent identifier instance.
  • record_hit – Record metadata retrieved via search.
  • links_factory – Factory function for record links.

Citeproc

CSL Citation Formatter serializer for records.

class invenio_records_rest.serializers.citeproc.CiteprocSerializer(serializer, record_format='csl')[source]

CSL Citation Formatter serializer for records.

In order to produce a formatted citation of a record through citeproc-py, we need a CSL-JSON or BibTeX serialized version of it. Since there may be already an implementation of such a serializer, it can be passed in the constructor of this class. This serializer has to implement a serialize method that returns the CSL-JSON/BibTeX result.

Initialize the inner record serializer.

Parameters:
  • serializer – Serializer object that does the record serialization to a format that citeproc-py can process (CSL-JSON or BibTeX). The object has to implement a serialize method that matches the signature of the serialize method of this class.
  • record_format – Format that the serializer produces.
serialize(pid, record, links_factory=None, **kwargs)[source]

Serialize a single record.

Parameters:
  • pid – Persistent identifier instance.
  • record – Record instance.
  • links_factory – Factory function for record links.

DataCite

Marshmallow based DataCite serializer for records.

class invenio_records_rest.serializers.datacite.BaseDataCiteSerializer(schema_class=<class 'invenio_records_rest.schemas.json.RecordSchemaJSONV1'>, **kwargs)[source]

Marshmallow based DataCite serializer for records.

Note: This serializer is not suitable for serializing large number of records.

Initialize record.

schema = None

Class variable to define which schema use.

serialize(pid, record, links_factory=None)[source]

Serialize a single record and persistent identifier.

Parameters:
  • pid – Persistent identifier instance.
  • record – Record instance.
  • links_factory – Factory function for record links.
serialize_oaipmh(pid, record)[source]

Serialize a single record for OAI-PMH.

Serialize a search result.

Parameters:
  • pid_fetcher – Persistent identifier fetcher.
  • search_result – Elasticsearch search result.
  • links – Dictionary of links to add to response.
version = None

Class variable to tell the version of the schema.

class invenio_records_rest.serializers.datacite.DataCite31Serializer(schema_class=<class 'invenio_records_rest.schemas.json.RecordSchemaJSONV1'>, **kwargs)[source]

Marshmallow DataCite serializer v3.1 for records.

Note: This serializer is not suitable for serializing large number of records.

Initialize record.

schema = <module 'datacite.schema31' from '/home/docs/checkouts/readthedocs.org/user_builds/invenio-records-rest/envs/latest/lib/python3.7/site-packages/datacite/schema31.py'>

Class variable to define which schema use.

version = '3.1'

Class variable to tell the version of the schema.

class invenio_records_rest.serializers.datacite.DataCite40Serializer(schema_class=<class 'invenio_records_rest.schemas.json.RecordSchemaJSONV1'>, **kwargs)[source]

Marshmallow DataCite serializer v4.0 for records.

Note: This serializer is not suitable for serializing large number of records.

Initialize record.

schema = <module 'datacite.schema40' from '/home/docs/checkouts/readthedocs.org/user_builds/invenio-records-rest/envs/latest/lib/python3.7/site-packages/datacite/schema40.py'>

Class variable to define which schema use.

version = '4.0'

Class variable to tell the version of the schema.

class invenio_records_rest.serializers.datacite.DataCite41Serializer(schema_class=<class 'invenio_records_rest.schemas.json.RecordSchemaJSONV1'>, **kwargs)[source]

Marshmallow DataCite serializer v4.1 for records.

Note: This serializer is not suitable for serializing large number of records.

Initialize record.

schema = <module 'datacite.schema41' from '/home/docs/checkouts/readthedocs.org/user_builds/invenio-records-rest/envs/latest/lib/python3.7/site-packages/datacite/schema41.py'>

Class variable to define which schema use.

version = '4.1'

Class variable to tell the version of the schema.

class invenio_records_rest.serializers.datacite.OAIDataCiteSerializer(serializer=None, datacentre=None, is_reference_quality='true')[source]

OAI DataCite serializer (only for OAI-PMH).

Initialize serializer.

serialize_oaipmh(pid, record)[source]

Serialize a single record for OAI-PMH.

DublinCore

Marshmallow based DublinCore serializer for records.

class invenio_records_rest.serializers.dc.DublinCoreSerializer(schema_class=<class 'invenio_records_rest.schemas.json.RecordSchemaJSONV1'>, **kwargs)[source]

Marshmallow based DublinCore serializer for records.

Note: This serializer is not suitable for serializing large number of records.

Initialize record.

serialize(pid, record, links_factory=None)[source]

Serialize a single record and persistent identifier.

Parameters:
  • pid – Persistent identifier instance.
  • record – Record instance.
  • links_factory – Factory function for record links.
serialize_oaipmh(pid, record)[source]

Serialize a single record for OAI-PMH.

Serialize a search result.

Parameters:
  • pid_fetcher – Persistent identifier fetcher.
  • search_result – Elasticsearch search result.
  • links – Dictionary of links to add to response.

JSON

Marshmallow based JSON serializer for records.

class invenio_records_rest.serializers.json.JSONSerializer(schema_class=<class 'invenio_records_rest.schemas.json.RecordSchemaJSONV1'>, **kwargs)[source]

Marshmallow based JSON serializer for records.

Initialize record.

class invenio_records_rest.serializers.json.JSONSerializerMixin[source]

Mixin serializing records as JSON.

serialize(pid, record, links_factory=None, **kwargs)[source]

Serialize a single record and persistent identifier.

Parameters:
  • pid – Persistent identifier instance.
  • record – Record instance.
  • links_factory – Factory function for record links.

Serialize a search result.

Parameters:
  • pid_fetcher – Persistent identifier fetcher.
  • search_result – Elasticsearch search result.
  • links – Dictionary of links to add to response.

JSON-LD

Marshmallow based JSON-LD serializer for records.

class invenio_records_rest.serializers.jsonld.JSONLDSerializer(context, expanded=True, **kwargs)[source]

JSON-LD serializer for records supporting Marshmallow schemas.

Initialize record.

Parameters:
  • context – JSON-LD context.
  • schema_class – Marshmallow schema.
  • expanded – expanded form, compacted else.
  • replace_refs – replace the $ref keys within the JSON.
class invenio_records_rest.serializers.jsonld.JSONLDTransformerMixin(context, expanded=True, **kwargs)[source]

JSON-LD serializer for records.

Note: This serializer is not suitable for serializing large number of records.

Initialize record.

Parameters:
  • context – JSON-LD context.
  • schema_class – Marshmallow schema.
  • expanded – expanded form, compacted else.
  • replace_refs – replace the $ref keys within the JSON.
expanded

Get JSON-LD expanded state.

transform_jsonld(obj)[source]

Compact JSON according to context.

transform_record(pid, record, links_factory=None, **kwargs)[source]

Transform record into an intermediate representation.

transform_search_hit(pid, record_hit, links_factory=None, **kwargs)[source]

Transform search result hit into an intermediate representation.

Marshmallow

Base class for Marshmallow based serializers.

class invenio_records_rest.serializers.marshmallow.MarshmallowMixin(schema_class=<class 'invenio_records_rest.schemas.json.RecordSchemaJSONV1'>, **kwargs)[source]

Base class for marshmallow serializers.

Initialize record.

dump(obj, context=None)[source]

Serialize object with schema.

transform_record(pid, record, links_factory=None, **kwargs)[source]

Transform record into an intermediate representation.

transform_search_hit(pid, record_hit, links_factory=None, **kwargs)[source]

Transform search result hit into an intermediate representation.

invenio_records_rest.serializers.marshmallow.MarshmallowSerializer

Marshmallow Serializer, only for backward compatibility.

alias of invenio_records_rest.serializers.marshmallow.MarshmallowMixin

CSV

Marshmallow based DublinCore serializer for records.

class invenio_records_rest.serializers.csv.CSVSerializer(*args, **kwargs)[source]

CSV serializer for records.

Note: This serializer is not suitable for serializing large number of records.

Initialize CSVSerializer.

Parameters:
  • csv_excluded_fields – list of paths of the fields that should be excluded from the final output
  • csv_included_fields – list of paths of the only fields that should be included in the final output
  • header_separator – separator that should be used when flattening nested dictionary keys
key_in_field(key, fields)[source]

Checks if the given key is contained within any of the fields.

process_dict(dictionary)[source]

Transform record dict with nested keys to a flat dict.

serialize(pid, record, links_factory=None)[source]

Serialize a single record and persistent identifier.

Parameters:
  • pid – Persistent identifier instance.
  • record – Record instance.
  • links_factory – Factory function for record links.

Serialize a search result.

Parameters:
  • pid_fetcher – Persistent identifier fetcher.
  • search_result – Elasticsearch search result.
  • links – Dictionary of links to add to response.
  • item_links_factory – Factory function for record links.
class invenio_records_rest.serializers.csv.Line[source]

Object that implements an interface the csv writer accepts.

Initialize.

read()[source]

Read a line.

write(line)[source]

Write a line.

Response

Serialization response factories.

Responsible for creating a HTTP response given the output of a serializer.

Add a Link HTTP header to a REST response.

Parameters:
  • response – REST response instance
  • links – Dictionary of links
invenio_records_rest.serializers.response.record_responsify(serializer, mimetype)[source]

Create a Records-REST response serializer.

Parameters:
  • serializer – Serializer instance.
  • mimetype – MIME type of response.
Returns:

Function that generates a record HTTP response.

invenio_records_rest.serializers.response.search_responsify(serializer, mimetype)[source]

Create a Records-REST search result response serializer.

Parameters:
  • serializer – Serializer instance.
  • mimetype – MIME type of response.
Returns:

Function that generates a record HTTP response.

Loaders

Loaders for deserializing records in the REST API.

invenio_records_rest.loaders.json_v1()

Simple example loader that will take any JSON.

invenio_records_rest.loaders.json_patch_loader()[source]

Dummy loader for json-patch requests.

Marshmallow

Marshmallow loader for record deserialization.

Use marshmallow schema to transform a JSON sent via the REST API from an external to an internal JSON presentation. The marshmallow schema further allows for advanced data validation.

exception invenio_records_rest.loaders.marshmallow.MarshmallowErrors(errors)[source]

Marshmallow validation errors.

Responsible for formatting a JSON response to a user when a validation error happens.

Store marshmallow errors.

get_body(environ=None)[source]

Get the request body.

next()[source]

Python 2.7 compatibility.

invenio_records_rest.loaders.marshmallow.json_patch_loader()[source]

Dummy loader for json-patch requests.

invenio_records_rest.loaders.marshmallow.marshmallow_loader(schema_class)[source]

Marshmallow loader for JSON requests.

Schemas

Marshmallow schemas for serialization.

class invenio_records_rest.schemas.RecordSchemaJSONV1(*, only: Union[Sequence[str], Set[str]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Dict[KT, VT] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: str = None)[source]

Schema for records v1 in JSON.

class invenio_records_rest.schemas.StrictKeysMixin(*, only: Union[Sequence[str], Set[str]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Dict[KT, VT] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: str = None)[source]

Ensure only valid keys exists.

check_unknown_fields(data, original_data, **kwargs)[source]

Check for unknown keys.

class invenio_records_rest.schemas.Nested(nested: Union[marshmallow.base.SchemaABC, type, str, Callable[[], marshmallow.base.SchemaABC]], *, default: Any = <marshmallow.missing>, only: Union[Sequence[str], Set[str]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, unknown: str = None, **kwargs)[source]

Custom Nested class to not recursively check errors.

New in version 1.2.0.

class invenio_records_rest.schemas.RecordMetadataSchemaJSONV1(*, only: Union[Sequence[str], Set[str]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Dict[KT, VT] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: str = None)[source]

Schema for records metadata v1 in JSON with injected PID value.

class Meta[source]

Meta attributes for the schema.

get_pid_field()[source]

Return pid_field value.

inject_pid(data, **kwargs)[source]

Inject context PID in the RECID field.

Fields

Custom marshmallow fields.

class invenio_records_rest.schemas.fields.DateString(format: str = None, **kwargs)[source]

ISO8601-formatted date string.

class invenio_records_rest.schemas.fields.Function(serialize: Union[Callable[[Any], Any], Callable[[Any, Dict[KT, VT]], Any]] = None, deserialize: Union[Callable[[Any], Any], Callable[[Any, Dict[KT, VT]], Any]] = None, **kwargs)[source]

Enhanced marshmallow Function field.

The main difference between the original marshmallow.fields.Function is for the deserialize function, which can now also point to a three-argument function, with the third argument being the original data that was passed to Schema.load. The following example better demonstrates how this works:

def serialize_foo(obj, context):
    return {'serialize_args': {'obj': obj, 'context': context}}

def deserialize_foo(value, context, data):
    return {'deserialize_args': {
        'value': value, 'context': context, 'data': data}}

class FooSchema(marshmallow.Schema):

    foo = Function(serialize_foo, deserialize_foo)

FooSchema().dump({'foo': 42}).data
{'foo': {
    'serialize_args': {
        'obj': {'foo': 42},
        'context': {}  # no context was passed
    }
}}

FooSchema().load({'foo': 42}).data
{'foo': {
    'deserialize_args': {
        'value': 42,
        'context': {},  # no context was passed
        'data': {'foo': 42},
    }
}}
class invenio_records_rest.schemas.fields.GenFunction(serialize: Union[Callable[[Any], Any], Callable[[Any, Dict[KT, VT]], Any]] = None, deserialize: Union[Callable[[Any], Any], Callable[[Any, Dict[KT, VT]], Any]] = None, **kwargs)[source]

Function field which is always deserialized.

class invenio_records_rest.schemas.fields.GenMethod(serialize: str = None, deserialize: str = None, **kwargs)[source]

Method field which is always deserialized.

class invenio_records_rest.schemas.fields.Method(serialize: str = None, deserialize: str = None, **kwargs)[source]

Enhanced marshmallow Method field.

The main difference between the original marshmallow.fields.Method is for the deserialize method, which can now also point to a two-argument method, with the second argument being the original data that was passed to Schema.load. The following example better demonstrates how this works:

class BarSchema(marshmallow.Schema):

    bar = Method('serialize_bar', 'deserialize_bar')

    # Exactly the same behavior as in ``marshmallow.fields.Method``
    def serialize_bar(self, obj):
        return {'serialize_args': {'obj': obj}}

    def deserialize_bar(self, value, data):
        return {'deserialize_args': {'value': value, 'data': data}}

BarSchema().dump({'bar': 42}).data
{'bar': {
    'serialize_args': {
        'obj': {'bar': 42}
    }
}}

BarSchema().load({'bar': 42}).data
{'bar': {
    'deserialize_args': {
        'data': {'bar': 42},
        'value': 42
    }
}}
class invenio_records_rest.schemas.fields.PersistentIdentifier(*args, **kwargs)[source]

Field to handle PersistentIdentifiers in records.

New in version 1.2.0.

Initialize field.

class invenio_records_rest.schemas.fields.SanitizedHTML(tags=None, attrs=None, *args, **kwargs)[source]

String field which strips sanitizes HTML using the bleach library.

Initialize field.

class invenio_records_rest.schemas.fields.SanitizedUnicode(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)[source]

String field that sanitizes and fixes problematic unicode characters.

is_valid_xml_char(char)[source]

Check if a character is valid based on the XML specification.

class invenio_records_rest.schemas.fields.TrimmedString(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)[source]

String field which strips whitespace the ends of the string.

Utils

General utility functions module.

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

Lazy PID resolver.

The PID will not be resolved until the data property is accessed.

Initialize with resolver object and the PID value.

Params resolver:
 Resolves for PID, see invenio_pidstore.resolver.Resolver.
Params value:PID value.
data[source]

Resolve PID from a value and return a tuple with PID and the 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, object_type='rec')[source]

Converter for PID values in the route mapping.

This class is a custom routing converter defining the ‘PID’ type. See http://werkzeug.pocoo.org/docs/0.12/routing/#custom-converters.

Use pid as a type in the route pattern, e.g.: the use of route decorator: @blueprint.route('/record/<pid(recid):pid_value>'), will match and resolve a path: /record/123456.

Initialize the converter.

to_python(value)[source]

Resolve PID value.

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

PIDConverter with support for path-like (with slashes) PID values.

This class is a custom routing converter defining the ‘PID’ type. See http://werkzeug.pocoo.org/docs/0.12/routing/#custom-converters.

Use pidpath as a type in the route patter, e.g.: the use of a route decorator: @blueprint.route('/record/<pidpath(recid):pid_value>'), will match and resolve a path containing a DOI: /record/10.1010/12345.

Initialize the converter.

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.make_comma_list_a_list(elements_to_rocess)[source]

Process a list with commas to simple list.

For example: [‘elem1’,’elem2,elem3’] => [‘elem1’, ‘elem2’, ‘elem3’]

Parameters:elements_to_rocess – list to process
Returns:processed list with elemnts separated
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

Records REST errors.

All error classes in this module are inheriting from invenio_rest.errors.RESTException or invenio_rest.errors.RESTValidationError.

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

Invalid request body.

Initialize RESTException.

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

Invalid query syntax.

Initialize RESTException.

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

JSONSchema validation error exception.

Initialize exception.

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

Deleted PID.

Initialize exception.

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

Non-existent PID.

Initialize exception.

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

PID missing object.

Initialize exception.

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

Base REST API PID exception class.

Initialize exception.

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

Invalid redirect for destination.

Initialize exception.

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

Invalid PID.

Initialize exception.

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

Unregistered PID.

Initialize exception.

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

Failed to patch JSON.

Initialize RESTException.

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

Search pagination error.

Initialize exception.

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

No such style.

Initialize exception.

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

Missing a context value when getting record suggestions.

Initialize exception.

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

No completion requested when getting record suggestions.

Initialize exception.

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

Failed to handle exception.

Initialize RESTException.

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

Creating record with unsupported media type.

Initialize exception.

Views

REST API resources.

class invenio_records_rest.views.RecordResource(read_permission_factory=None, update_permission_factory=None, delete_permission_factory=None, default_media_type=None, links_factory=None, loaders=None, search_class=None, indexer_class=None, **kwargs)[source]

Resource for record items.

Constructor.

delete(pid, record, **kwargs)[source]

Delete a record.

Permissions: delete_permission_factory

Procedure description:

  1. The record is resolved reading the pid value from the url.
  2. The ETag is checked.
  3. The record is deleted.
  4. All PIDs are marked as DELETED.
Parameters:
  • pid – Persistent identifier for record.
  • record – Record object.
get(pid, record, **kwargs)[source]

Get a record.

Permissions: read_permission_factory

Procedure description:

  1. The record is resolved reading the pid value from the url.
  2. The ETag and If-Modifed-Since is checked.
  3. The HTTP response is built with the help of the link factory.
Parameters:
  • pid – Persistent identifier for record.
  • record – Record object.
Returns:

The requested record.

patch(pid, record, **kwargs)[source]

Modify a record.

Permissions: update_permission_factory

The data should be a JSON-patch, which will be applied to the record. Requires header Content-Type: application/json-patch+json.

Procedure description:

  1. The record is deserialized using the proper loader.
  2. The ETag is checked.
  3. The record is patched.
  4. The HTTP response is built with the help of the link factory.
Parameters:
  • pid – Persistent identifier for record.
  • record – Record object.
Returns:

The modified record.

put(pid, record, **kwargs)[source]

Replace a record.

Permissions: update_permission_factory

The body should be a JSON object, which will fully replace the current record metadata.

Procedure description:

  1. The ETag is checked.
  2. The record is updated by calling the record API clear(), update() and then commit().
  3. The HTTP response is built with the help of the link factory.
Parameters:
  • pid – Persistent identifier for record.
  • record – Record object.
Returns:

The modified record.

class invenio_records_rest.views.RecordsListOptionsResource(search_index=None, max_result_window=None, default_media_type=None, search_media_types=None, item_media_types=None)[source]

Resource for displaying options about records list/item views.

Initialize method view.

get()[source]

Get options.

class invenio_records_rest.views.RecordsListResource(minter_name=None, pid_type=None, pid_fetcher=None, read_permission_factory=None, create_permission_factory=None, list_permission_factory=None, search_class=None, record_serializers=None, record_loaders=None, search_serializers=None, default_media_type=None, max_result_window=None, search_factory=None, item_links_factory=None, record_class=None, indexer_class=None, **kwargs)[source]

Resource for records listing.

Constructor.

get(pagination=None, **kwargs)[source]

Search records.

Permissions: the list_permission_factory permissions are
checked.
Returns:Search result containing hits and aggregations as returned by invenio-search.
post(**kwargs)[source]

Create a record.

Permissions: create_permission_factory

Procedure description:

  1. First of all, the create_permission_factory permissions are
    checked.
  2. Then, the record is deserialized by the proper loader.
  3. A second call to the create_permission_factory factory is done:
    it differs from the previous call because this time the record is passed as parameter.
  4. A uuid is generated for the record and the minter is called.
  5. The record class is called to create the record.
  6. The HTTP response is built with the help of the item link factory.
Returns:The created record.
class invenio_records_rest.views.SuggestResource(suggesters, search_class=None, **kwargs)[source]

Resource for records suggests.

Constructor.

get(**kwargs)[source]

Get suggestions.

invenio_records_rest.views.create_blueprint(endpoints)[source]

Create Invenio-Records-REST blueprint.

Params endpoints:
 Dictionary representing the endpoints configuration.
Returns:Configured blueprint.
invenio_records_rest.views.create_blueprint_from_app(app)[source]

Create Invenio-Records-REST blueprint from a Flask application.

Note

This function assumes that the application has loaded all extensions that want to register REST endpoints via the RECORDS_REST_ENDPOINTS configuration variable.

Params app:A Flask application.
Returns:Configured blueprint.
invenio_records_rest.views.create_error_handlers(blueprint, error_handlers_registry=None)[source]

Create error handlers on blueprint.

Params blueprint:
 

Records API blueprint.

Params error_handlers_registry:
 

Configuration of error handlers per exception or HTTP status code and view name.

The dictionary has the following structure:

{
    SomeExceptionClass: {
        'recid_list': 'path.to.error_handler_function_foo',
        'recid_item': 'path.to.error_handler_function_foo',
    },
    410: {
        'custom_pid_list': 'path.to.error_handler_function_bar',
        'custom_pid_item': 'path.to.error_handler_function_bar',
        'recid_item': 'path.to.error_handler_function_baz',
        'recid_list': 'path.to.error_handler_function_baz',
    },
}
Returns:

Configured blueprint.

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, list_permission_factory_imp=None, record_class=None, record_serializers=None, record_serializers_aliases=None, record_loaders=None, search_class=None, indexer_class=<class 'invenio_indexer.api.RecordIndexer'>, search_serializers=None, search_serializers_aliases=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.
  • list_permission_factory_imp – Import path to factory that creates a list permission object for a given index/list.
  • default_endpoint_prefix – ignored.
  • record_class – A record API class or importable string used when creating new records.
  • record_serializers – Serializers used for records.
  • record_serializers_aliases – A mapping of values of the defined query arg (see config.REST_MIMETYPE_QUERY_ARG_NAME) to valid mimetypes for record item serializers: dict(alias -> mimetype).
  • record_loaders – It contains the list of record deserializers 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 of ElasticSearch DSL library.
  • indexer_class – Import path or class object for the object in charge of indexing records. The default indexer is invenio_indexer.api.RecordIndexer.
  • search_serializers – Serializers used for search results.
  • search_serializers_aliases – A mapping of values of the defined query arg (see config.REST_MIMETYPE_QUERY_ARG_NAME) to valid mimetypes for records search serializers: dict(alias -> mimetype).
  • 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 queries.
  • 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.

invenio_records_rest.views.elasticsearch_query_parsing_exception_handler(error)[source]

Handle query parsing exceptions from ElasticSearch.

invenio_records_rest.views.need_record_permission(factory_name)[source]

Decorator checking that the user has the required permissions on record.

Parameters:factory_name – name of the permission factory.
invenio_records_rest.views.pass_record(f)[source]

Decorator to retrieve persistent identifier and record.

This decorator will resolve the pid_value parameter from the route pattern and resolve it to a PID and a record, which are then available in the decorated function as pid and record kwargs respectively.

invenio_records_rest.views.use_paginate_args(default_size=25, max_results=10000)[source]

Get and validate pagination arguments.

invenio_records_rest.views.verify_record_permission(permission_factory, record)[source]

Check that the current user has the required permissions on record.

In case the permission check fails, an Flask abort is launched. If the user was previously logged-in, a HTTP error 403 is returned. Otherwise, is returned a HTTP error 401.

Parameters:
  • permission_factory – permission factory used to check permissions.
  • record – record whose access is limited.

Permissions

Permissions are handled by the following decorator, which is used in the record’s REST resources:

invenio_records_rest.views.need_record_permission(factory_name)[source]

Decorator checking that the user has the required permissions on record.

Parameters:factory_name – name of the permission factory.

each resource method is checking the permissions through this decorator, with read_permission_factory, create_permission_factory, update_permission_factory and delete_permission_factory as argument, where the implementation of each can be configured for each REST endpoint with invenio_records_rest.config.RECORDS_REST_ENDPOINTS (using {read,create,update,delete}_permission_factory_imp keys).

For reference on each resource method and the default permission factory, refer to the methods’ docstrings in the Views section above.