Skip to content

API reference

Generated from the docstrings with mkdocstrings.

Client

aireloom.AireloomClient

Bases: BaseApiClient

Client for the OpenAIRE Graph API (V4) and the Scholexplorer API.

Entity resources are available as typed attributes; single-entity lookups go through the V3 by-id routes because V4 has none. Authentication resolves in the constructor: set openaire_refresh_token / refresh_token for OAuth2 refresh-token access, or set both openaire_client_id and openaire_client_secret (settings, AIRELOOM_OPENAIRE_CLIENT_ID / AIRELOOM_OPENAIRE_CLIENT_SECRET, or client_id / client_secret) for OAuth2 client-credentials access against the Keycloak token endpoint; partial client credentials raise :class:ConfigurationError, and without credentials the client is anonymous. An explicit auth_strategy always wins.

The Scholix resource talks to the Scholexplorer host through a second internal client that shares settings and credentials but throttles itself to one request per second. See the package README and docs for usage examples of both the async and the sync variants.

Source code in packages/aireloom/src/aireloom/_async/client.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
class AireloomClient(BaseApiClient):
    """Client for the OpenAIRE Graph API (V4) and the Scholexplorer API.

    Entity resources are available as typed attributes; single-entity lookups
    go through the V3 by-id routes because V4 has none. Authentication
    resolves in the constructor: set ``openaire_refresh_token`` /
    ``refresh_token`` for OAuth2 refresh-token access, or set both
    ``openaire_client_id`` and ``openaire_client_secret`` (settings,
    ``AIRELOOM_OPENAIRE_CLIENT_ID`` / ``AIRELOOM_OPENAIRE_CLIENT_SECRET``, or
    ``client_id`` / ``client_secret``) for OAuth2 client-credentials access
    against the Keycloak token endpoint; partial client credentials raise
    :class:`ConfigurationError`, and without credentials the client is
    anonymous. An explicit ``auth_strategy`` always wins.

    The Scholix resource talks to the Scholexplorer host through a second
    internal client that shares settings and credentials but throttles itself
    to one request per second. See the package README and docs for usage
    examples of both the async and the sync variants.
    """

    def __init__(
        self,
        settings: AireloomSettings | None = None,
        auth: AuthStrategy | None = None,
        *,
        auth_strategy: AuthStrategy | None = None,
        base_url: str | None = None,
        scholix_base_url: str | None = None,
        mailto: str | None = None,
        client_id: str | None = None,
        client_secret: str | None = None,
        refresh_token: str | None = None,
        http_client: httpx.AsyncClient | None = None,
    ) -> None:
        """Build the client from settings, resolving credentials immediately.

        ``settings`` defaults to :func:`aireloom.config.get_settings`, which
        reads ``AIRELOOM_*`` environment variables and ``.env``. Keyword
        overrides (``base_url``, ``scholix_base_url``, ``mailto``,
        ``client_id``, ``client_secret``, ``refresh_token``) take precedence
        over ``settings``. Pass ``auth_strategy`` for a custom auth strategy
        (``auth`` is a deprecated alias).
        """
        if auth is not None and auth_strategy is not None:
            raise ConfigurationError(
                "Pass either 'auth_strategy' or the deprecated 'auth' parameter, "
                "not both."
            )
        if auth is not None:
            warnings.warn(
                "The 'auth' parameter is deprecated; use 'auth_strategy' instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            explicit_auth: AuthStrategy | None = auth
        else:
            explicit_auth = auth_strategy

        resolved = settings or get_settings()
        overrides: dict[str, str] = {}
        if base_url is not None:
            overrides["base_url"] = base_url
        if scholix_base_url is not None:
            overrides["scholix_base_url"] = scholix_base_url
        if mailto is not None:
            overrides["mailto"] = mailto
        if client_id is not None:
            overrides["openaire_client_id"] = client_id
        if client_secret is not None:
            overrides["openaire_client_secret"] = client_secret
        if refresh_token is not None:
            overrides["openaire_refresh_token"] = refresh_token
        if overrides:
            resolved = resolved.model_copy(update=overrides)
        strategy = (
            explicit_auth if explicit_auth is not None else _resolve_auth(resolved)
        )
        super().__init__(
            base_url=resolved.base_url,
            settings=resolved,
            unwrapper=OpenAireUnwrapper(),
            auth=strategy,
            http_client=http_client,
        )
        self._scholix_api = BaseApiClient(
            base_url=resolved.scholix_base_url,
            settings=resolved.model_copy(
                update={
                    "max_requests_per_second": resolved.scholix_max_requests_per_second
                }
            ),
            unwrapper=ScholixUnwrapper(),
            auth=strategy,
        )
        auth_label = (
            "anonymous" if isinstance(strategy, NoAuth) else type(strategy).__name__
        )
        logger.debug("%s initialized (%s).", type(self).__name__, auth_label)

    async def request(
        self,
        method: str,
        path: str,
        *,
        params: Mapping[str, Any] | None = None,
        json: Any | None = None,
        data: Mapping[str, Any] | None = None,
        content: str | bytes | None = None,
        headers: Mapping[str, str] | None = None,
        timeout: float | httpx.Timeout | None = None,
        retry: bool | None = None,
        follow_redirects: bool | None = None,
    ) -> httpx.Response:
        """Send a request through the core retry pipeline.

        V4 accepts ``mailto`` for polite-pool admission (V3 rejects it), so the
        configured contact address is attached to ``v4/`` requests only.
        """
        effective_params: Mapping[str, Any] | None = params
        if path.lstrip("/").startswith("v4/") and self._settings.mailto:
            if params is None:
                effective_params = {"mailto": self._settings.mailto}
            elif isinstance(params, Mapping):
                if "mailto" not in params:
                    effective_params = {"mailto": self._settings.mailto, **params}
            else:
                qp = httpx.QueryParams(params)
                if "mailto" not in qp:
                    effective_params = qp.set("mailto", self._settings.mailto)
        return await super().request(
            method,
            path,
            params=effective_params,
            json=json,
            data=data,
            content=content,
            headers=headers,
            timeout=timeout,
            retry=retry,
            follow_redirects=follow_redirects,
        )

    @functools.cached_property
    def _links(self) -> LinksResource:
        return LinksResource(self)

    @functools.cached_property
    def research_products(self) -> ResearchProductsResource:
        """Search, iterate, and batch-fetch research products; links helpers."""
        return ResearchProductsResource(self, self._links)

    @functools.cached_property
    def projects(self) -> ProjectsResource:
        """Search and iterate OpenAIRE projects."""
        return ProjectsResource(self)

    @functools.cached_property
    def organizations(self) -> OrganizationsResource:
        """Search and iterate OpenAIRE organizations."""
        return OrganizationsResource(self)

    @functools.cached_property
    def data_sources(self) -> DataSourcesResource:
        """Search and iterate OpenAIRE data sources."""
        return DataSourcesResource(self)

    @functools.cached_property
    def persons(self) -> PersonsResource:
        """Search and iterate OpenAIRE persons."""
        return PersonsResource(self)

    @functools.cached_property
    def scholix(self) -> ScholixResource:
        """Search Scholix links on the Scholexplorer host (V3, V2 for linkProvider)."""
        return ScholixResource(self._scholix_api)

    async def aclose(self) -> None:
        """Close both the Graph and the Scholix HTTP clients."""
        try:
            await super().aclose()
        finally:
            await self._scholix_api.aclose()

request(method, path, *, params=None, json=None, data=None, content=None, headers=None, timeout=None, retry=None, follow_redirects=None) async

Send a request through the core retry pipeline.

V4 accepts mailto for polite-pool admission (V3 rejects it), so the configured contact address is attached to v4/ requests only.

Source code in packages/aireloom/src/aireloom/_async/client.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
async def request(
    self,
    method: str,
    path: str,
    *,
    params: Mapping[str, Any] | None = None,
    json: Any | None = None,
    data: Mapping[str, Any] | None = None,
    content: str | bytes | None = None,
    headers: Mapping[str, str] | None = None,
    timeout: float | httpx.Timeout | None = None,
    retry: bool | None = None,
    follow_redirects: bool | None = None,
) -> httpx.Response:
    """Send a request through the core retry pipeline.

    V4 accepts ``mailto`` for polite-pool admission (V3 rejects it), so the
    configured contact address is attached to ``v4/`` requests only.
    """
    effective_params: Mapping[str, Any] | None = params
    if path.lstrip("/").startswith("v4/") and self._settings.mailto:
        if params is None:
            effective_params = {"mailto": self._settings.mailto}
        elif isinstance(params, Mapping):
            if "mailto" not in params:
                effective_params = {"mailto": self._settings.mailto, **params}
        else:
            qp = httpx.QueryParams(params)
            if "mailto" not in qp:
                effective_params = qp.set("mailto", self._settings.mailto)
    return await super().request(
        method,
        path,
        params=effective_params,
        json=json,
        data=data,
        content=content,
        headers=headers,
        timeout=timeout,
        retry=retry,
        follow_redirects=follow_redirects,
    )

aclose() async

Close both the Graph and the Scholix HTTP clients.

Source code in packages/aireloom/src/aireloom/_async/client.py
235
236
237
238
239
240
async def aclose(self) -> None:
    """Close both the Graph and the Scholix HTTP clients."""
    try:
        await super().aclose()
    finally:
        await self._scholix_api.aclose()

Settings

aireloom.AireloomSettings

Bases: BaseApiSettings

Tunable client behavior for the OpenAIRE Graph and Scholexplorer APIs.

Every field can be set through an environment variable prefixed with AIRELOOM_ (for example AIRELOOM_OPENAIRE_CLIENT_ID) or a .env file in the working directory.

Source code in packages/aireloom/src/aireloom/config.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class AireloomSettings(BaseApiSettings):
    """Tunable client behavior for the OpenAIRE Graph and Scholexplorer APIs.

    Every field can be set through an environment variable prefixed with
    ``AIRELOOM_`` (for example ``AIRELOOM_OPENAIRE_CLIENT_ID``) or a ``.env``
    file in the working directory.
    """

    model_config = SettingsConfigDict(
        env_prefix="AIRELOOM_",
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore",
    )

    base_url: str = DEFAULT_GRAPH_BASE_URL
    scholix_base_url: str = DEFAULT_SCHOLIX_BASE_URL

    # OAuth2 client credentials (registered service) or refresh token. Without
    # credentials the client stays anonymous; partial client credentials raise
    # ConfigurationError.
    openaire_client_id: str | None = None
    openaire_client_secret: str | None = None
    openaire_refresh_token: str | None = Field(default=None, repr=False)
    token_url: str = DEFAULT_TOKEN_URL

    # D-15: OpenAIRE allows about 7200 requests per rolling hour.
    max_requests_per_second: float | None = 2.0
    max_concurrency: int = 4

    # The Scholexplorer host sends no rate-limit headers, so self-throttle.
    scholix_max_requests_per_second: float | None = 1.0

Resources

aireloom.ResearchProductsResource

Bases: GraphResource[ResearchProduct]

V4 research products endpoint: search, iterate, count, facets, group_by.

get(id) reads the V3 by-id route because V4 has no by-id endpoints. Batch lookups use OR expressions over id and ids.doi.

Source code in packages/aireloom/src/aireloom/_async/resources.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
class ResearchProductsResource(GraphResource[ResearchProduct]):
    """V4 research products endpoint: search, iterate, count, facets, group_by.

    ``get(id)`` reads the V3 by-id route because V4 has no by-id endpoints.
    Batch lookups use OR expressions over ``id`` and ``ids.doi``.
    """

    path = "v4/research-products"
    model = ResearchProduct
    filters_model = ResearchProductsFilters
    sort_fields = frozenset(
        {
            "relevance",
            "publication_date",
            "date_of_collection",
            "citation_count",
            "influence",
            "popularity",
            "impulse",
        }
    )
    batch_size = 50

    def __init__(self, client: BaseApiClient, links: LinksResource) -> None:
        super().__init__(client)
        self._links = links

    def record_keys(self, entity: ResearchProduct, field: str) -> list[str]:
        if field == "ids.doi":
            # Deduplicated records carry several DOIs; batch_get keeps the requested one.
            return [normalize_doi(doi) for doi in entity.all_dois]
        return super().record_keys(entity, field)

    async def batch_get_by_doi(
        self,
        dois: list[str] | tuple[str, ...],
        *,
        batch_size: int | None = None,
        concurrency: int = 4,
    ) -> dict[str, ResearchProduct]:
        """Fetch research products for many DOIs in bounded, concurrent chunks.

        Keys are bare, lowercased DOIs; missing DOIs are absent from the
        result. The request goes out as ``filter=ids.doi:a|b|c``.
        """
        normalized = list(dict.fromkeys(normalize_doi(doi) for doi in dois))
        return await self.batch_get(
            normalized, field="ids.doi", batch_size=batch_size, concurrency=concurrency
        )

    async def by_orcid(self, orcid: str, *, limit: int = 100) -> list[ResearchProduct]:
        """Return research products whose authorship carries ``orcid``.

        Accepts any spelling ``bibliofabric.ids.normalize_orcid`` handles
        (bare, dashed, or an ``https://orcid.org/`` URL); the filter sends
        the hyphenated form via the V4 ``authorships.author.orcid`` field and
        paginates via cursor when ``limit`` exceeds 100.
        """
        page_size = min(limit, self.dialect.max_page_size) if limit > 0 else None
        return await self.collect(
            ResearchProductsFilters(authorships_author_orcid=normalize_orcid(orcid)),
            limit=limit,
            page_size=page_size,
        )

    async def get_fields(
        self,
        ids: Sequence[str],
        fields: Sequence[str],
        *,
        batch_size: int | None = None,
        concurrency: int = 4,
    ) -> list[ResearchProduct]:
        """Sparse-fetch ``fields`` for known ids in bounded, concurrent chunks.

        Combines the V4 ``select`` parameter with an ``id`` OR-filter (at most
        50 ids per chunk). The returned records carry only the requested
        fields; every other model field stays at its default.
        """
        selected = [field.strip() for field in fields if field and field.strip()]
        if not selected:
            raise ConfigurationError("get_fields() requires at least one field name.")
        size = self.batch_size if batch_size is None else batch_size
        if size <= 0 or size > MAX_OR_VALUES:
            raise ConfigurationError(
                f"batch_size must be between 1 and {MAX_OR_VALUES}, got {size}."
            )
        if concurrency <= 0:
            raise ConfigurationError(
                f"concurrency must be positive, got {concurrency}."
            )
        wanted = list(
            dict.fromkeys(norm for raw in ids if (norm := self.normalize_id(raw)))
        )
        if not wanted:
            return []
        chunks = [wanted[start : start + size] for start in range(0, len(wanted), size)]

        async def fetch_chunk(chunk: list[str]) -> list[ResearchProduct]:
            page = await self.search(
                {"id": chunk}, select=selected, page_size=len(chunk)
            )
            return page.results

        chunk_results = await run_bounded(fetch_chunk, chunks, concurrency)
        return [record for group in chunk_results for record in group]

    async def search_links(
        self,
        filters: LinksFilters | Mapping[str, Any] | None = None,
        *,
        page: int | None = None,
        page_size: int | None = None,
    ) -> Page[Relation]:
        """Fetch one page of relations from the Graph links route."""
        return await self._links.search(filters, page=page, page_size=page_size)

    def iterate_links(
        self,
        filters: LinksFilters | Mapping[str, Any] | None = None,
        *,
        page_size: int | None = None,
        limit: int | None = None,
        on_error: OnError = "raise",
        failures: list[tuple[dict[str, Any], Exception]] | None = None,
        on_page: Callable[[int, str | None], Any] | None = None,
    ) -> AsyncIterator[Relation]:
        """Iterate over all relations matching ``filters``, 99 per page.

        See :class:`LinksResource` for the missing-sort hazard of this
        page-based route.
        """
        return self._links.iterate(
            filters,
            page_size=page_size,
            limit=limit,
            on_error=on_error,
            failures=failures,
            on_page=on_page,
        )

    async def get_relations_info(self) -> list[RelationInfo]:
        """Return the relation types the links endpoint can produce."""
        return await self._links.get_relations_info()

batch_get_by_doi(dois, *, batch_size=None, concurrency=4) async

Fetch research products for many DOIs in bounded, concurrent chunks.

Keys are bare, lowercased DOIs; missing DOIs are absent from the result. The request goes out as filter=ids.doi:a|b|c.

Source code in packages/aireloom/src/aireloom/_async/resources.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
async def batch_get_by_doi(
    self,
    dois: list[str] | tuple[str, ...],
    *,
    batch_size: int | None = None,
    concurrency: int = 4,
) -> dict[str, ResearchProduct]:
    """Fetch research products for many DOIs in bounded, concurrent chunks.

    Keys are bare, lowercased DOIs; missing DOIs are absent from the
    result. The request goes out as ``filter=ids.doi:a|b|c``.
    """
    normalized = list(dict.fromkeys(normalize_doi(doi) for doi in dois))
    return await self.batch_get(
        normalized, field="ids.doi", batch_size=batch_size, concurrency=concurrency
    )

by_orcid(orcid, *, limit=100) async

Return research products whose authorship carries orcid.

Accepts any spelling bibliofabric.ids.normalize_orcid handles (bare, dashed, or an https://orcid.org/ URL); the filter sends the hyphenated form via the V4 authorships.author.orcid field and paginates via cursor when limit exceeds 100.

Source code in packages/aireloom/src/aireloom/_async/resources.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
async def by_orcid(self, orcid: str, *, limit: int = 100) -> list[ResearchProduct]:
    """Return research products whose authorship carries ``orcid``.

    Accepts any spelling ``bibliofabric.ids.normalize_orcid`` handles
    (bare, dashed, or an ``https://orcid.org/`` URL); the filter sends
    the hyphenated form via the V4 ``authorships.author.orcid`` field and
    paginates via cursor when ``limit`` exceeds 100.
    """
    page_size = min(limit, self.dialect.max_page_size) if limit > 0 else None
    return await self.collect(
        ResearchProductsFilters(authorships_author_orcid=normalize_orcid(orcid)),
        limit=limit,
        page_size=page_size,
    )

get_fields(ids, fields, *, batch_size=None, concurrency=4) async

Sparse-fetch fields for known ids in bounded, concurrent chunks.

Combines the V4 select parameter with an id OR-filter (at most 50 ids per chunk). The returned records carry only the requested fields; every other model field stays at its default.

Source code in packages/aireloom/src/aireloom/_async/resources.py
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
async def get_fields(
    self,
    ids: Sequence[str],
    fields: Sequence[str],
    *,
    batch_size: int | None = None,
    concurrency: int = 4,
) -> list[ResearchProduct]:
    """Sparse-fetch ``fields`` for known ids in bounded, concurrent chunks.

    Combines the V4 ``select`` parameter with an ``id`` OR-filter (at most
    50 ids per chunk). The returned records carry only the requested
    fields; every other model field stays at its default.
    """
    selected = [field.strip() for field in fields if field and field.strip()]
    if not selected:
        raise ConfigurationError("get_fields() requires at least one field name.")
    size = self.batch_size if batch_size is None else batch_size
    if size <= 0 or size > MAX_OR_VALUES:
        raise ConfigurationError(
            f"batch_size must be between 1 and {MAX_OR_VALUES}, got {size}."
        )
    if concurrency <= 0:
        raise ConfigurationError(
            f"concurrency must be positive, got {concurrency}."
        )
    wanted = list(
        dict.fromkeys(norm for raw in ids if (norm := self.normalize_id(raw)))
    )
    if not wanted:
        return []
    chunks = [wanted[start : start + size] for start in range(0, len(wanted), size)]

    async def fetch_chunk(chunk: list[str]) -> list[ResearchProduct]:
        page = await self.search(
            {"id": chunk}, select=selected, page_size=len(chunk)
        )
        return page.results

    chunk_results = await run_bounded(fetch_chunk, chunks, concurrency)
    return [record for group in chunk_results for record in group]

get_relations_info() async

Return the relation types the links endpoint can produce.

Source code in packages/aireloom/src/aireloom/_async/resources.py
499
500
501
async def get_relations_info(self) -> list[RelationInfo]:
    """Return the relation types the links endpoint can produce."""
    return await self._links.get_relations_info()

Iterate over all relations matching filters, 99 per page.

See :class:LinksResource for the missing-sort hazard of this page-based route.

Source code in packages/aireloom/src/aireloom/_async/resources.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def iterate_links(
    self,
    filters: LinksFilters | Mapping[str, Any] | None = None,
    *,
    page_size: int | None = None,
    limit: int | None = None,
    on_error: OnError = "raise",
    failures: list[tuple[dict[str, Any], Exception]] | None = None,
    on_page: Callable[[int, str | None], Any] | None = None,
) -> AsyncIterator[Relation]:
    """Iterate over all relations matching ``filters``, 99 per page.

    See :class:`LinksResource` for the missing-sort hazard of this
    page-based route.
    """
    return self._links.iterate(
        filters,
        page_size=page_size,
        limit=limit,
        on_error=on_error,
        failures=failures,
        on_page=on_page,
    )

Fetch one page of relations from the Graph links route.

Source code in packages/aireloom/src/aireloom/_async/resources.py
465
466
467
468
469
470
471
472
473
async def search_links(
    self,
    filters: LinksFilters | Mapping[str, Any] | None = None,
    *,
    page: int | None = None,
    page_size: int | None = None,
) -> Page[Relation]:
    """Fetch one page of relations from the Graph links route."""
    return await self._links.search(filters, page=page, page_size=page_size)

aireloom.ProjectsResource

Bases: GraphResource[Project]

V4 projects endpoint: search, iterate, count, facets, group_by.

get(id) reads the V3 by-id route because V4 has no by-id endpoints.

Source code in packages/aireloom/src/aireloom/_async/resources.py
309
310
311
312
313
314
315
316
317
318
class ProjectsResource(GraphResource[Project]):
    """V4 projects endpoint: search, iterate, count, facets, group_by.

    ``get(id)`` reads the V3 by-id route because V4 has no by-id endpoints.
    """

    path = "v4/projects"
    model = Project
    filters_model = ProjectsFilters
    sort_fields = frozenset({"relevance", "start_date", "end_date"})

aireloom.OrganizationsResource

Bases: GraphResource[Organization]

V4 organizations endpoint: search, iterate, count, facets, group_by.

get(id) reads the V3 by-id route because V4 has no by-id endpoints.

Source code in packages/aireloom/src/aireloom/_async/resources.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
class OrganizationsResource(GraphResource[Organization]):
    """V4 organizations endpoint: search, iterate, count, facets, group_by.

    ``get(id)`` reads the V3 by-id route because V4 has no by-id endpoints.
    """

    path = "v4/organizations"
    model = Organization
    filters_model = OrganizationsFilters

    async def find_variants(
        self,
        names: Sequence[str],
        *,
        country: str | None = None,
        page_size: int | None = None,
    ) -> list[Organization]:
        """Search each name fragment and return deduplicated organizations.

        Records are deduplicated by exact ``id`` keeping the first match;
        ``pending_org_::`` records are kept on purpose. They carry
        organization-project links that the canonical merged record lost,
        which makes them the main source of undercounted org-project
        links, so callers decide how to merge them.
        """
        filters = {"country": country} if country else None
        found: dict[str, Organization] = {}
        for name in names:
            page = await self.search(filters, query=name, page_size=page_size)
            for org in page.results:
                found.setdefault(org.id, org)
        return list(found.values())

find_variants(names, *, country=None, page_size=None) async

Search each name fragment and return deduplicated organizations.

Records are deduplicated by exact id keeping the first match; pending_org_:: records are kept on purpose. They carry organization-project links that the canonical merged record lost, which makes them the main source of undercounted org-project links, so callers decide how to merge them.

Source code in packages/aireloom/src/aireloom/_async/resources.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
async def find_variants(
    self,
    names: Sequence[str],
    *,
    country: str | None = None,
    page_size: int | None = None,
) -> list[Organization]:
    """Search each name fragment and return deduplicated organizations.

    Records are deduplicated by exact ``id`` keeping the first match;
    ``pending_org_::`` records are kept on purpose. They carry
    organization-project links that the canonical merged record lost,
    which makes them the main source of undercounted org-project
    links, so callers decide how to merge them.
    """
    filters = {"country": country} if country else None
    found: dict[str, Organization] = {}
    for name in names:
        page = await self.search(filters, query=name, page_size=page_size)
        for org in page.results:
            found.setdefault(org.id, org)
    return list(found.values())

aireloom.DataSourcesResource

Bases: GraphResource[DataSource]

V4 data sources endpoint: search, iterate, count, facets, group_by.

get(id) reads the V3 by-id route because V4 has no by-id endpoints.

Source code in packages/aireloom/src/aireloom/_async/resources.py
219
220
221
222
223
224
225
226
227
class DataSourcesResource(GraphResource[DataSource]):
    """V4 data sources endpoint: search, iterate, count, facets, group_by.

    ``get(id)`` reads the V3 by-id route because V4 has no by-id endpoints.
    """

    path = "v4/datasources"
    model = DataSource
    filters_model = DataSourcesFilters

aireloom.PersonsResource

Bases: GraphResource[Person]

V4 persons endpoint: search, iterate, count, facets, group_by.

get(id) reads the V3 by-id route because V4 has no by-id endpoints. Batch lookups by ORCID use an OR expression over ids.original.

Source code in packages/aireloom/src/aireloom/_async/resources.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
class PersonsResource(GraphResource[Person]):
    """V4 persons endpoint: search, iterate, count, facets, group_by.

    ``get(id)`` reads the V3 by-id route because V4 has no by-id endpoints.
    Batch lookups by ORCID use an OR expression over ``ids.original``.
    """

    path = "v4/persons"
    model = Person
    filters_model = PersonsFilters
    batch_size = 50

    def record_keys(self, entity: Person, field: str) -> list[str]:
        if field == "ids.original":
            keys = [normalize_orcid(value) for value in entity.originalId]
            keys.extend(
                normalize_orcid(entry.value)
                for entry in entity.pid
                if entry.typeCode.lower() == "orcid" and entry.value
            )
            return list(dict.fromkeys(keys))
        return super().record_keys(entity, field)

    async def batch_get_by_orcid(
        self,
        orcids: list[str] | tuple[str, ...],
        *,
        batch_size: int | None = None,
        concurrency: int = 4,
    ) -> dict[str, Person]:
        """Fetch person records for many ORCID iDs in bounded, concurrent chunks.

        Accepts any spelling ``bibliofabric.ids.normalize_orcid`` handles. Keys
        are hyphenated ORCID iDs; ORCIDs without a person record are absent from
        the result. The request goes out as ``filter=ids.original:a|b|c``.
        """
        normalized = list(dict.fromkeys(normalize_orcid(orcid) for orcid in orcids))
        return await self.batch_get(
            normalized,
            field="ids.original",
            batch_size=batch_size,
            concurrency=concurrency,
        )

batch_get_by_orcid(orcids, *, batch_size=None, concurrency=4) async

Fetch person records for many ORCID iDs in bounded, concurrent chunks.

Accepts any spelling bibliofabric.ids.normalize_orcid handles. Keys are hyphenated ORCID iDs; ORCIDs without a person record are absent from the result. The request goes out as filter=ids.original:a|b|c.

Source code in packages/aireloom/src/aireloom/_async/resources.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
async def batch_get_by_orcid(
    self,
    orcids: list[str] | tuple[str, ...],
    *,
    batch_size: int | None = None,
    concurrency: int = 4,
) -> dict[str, Person]:
    """Fetch person records for many ORCID iDs in bounded, concurrent chunks.

    Accepts any spelling ``bibliofabric.ids.normalize_orcid`` handles. Keys
    are hyphenated ORCID iDs; ORCIDs without a person record are absent from
    the result. The request goes out as ``filter=ids.original:a|b|c``.
    """
    normalized = list(dict.fromkeys(normalize_orcid(orcid) for orcid in orcids))
    return await self.batch_get(
        normalized,
        field="ids.original",
        batch_size=batch_size,
        concurrency=concurrency,
    )

aireloom.LinksResource

Bases: ResourceClient[Relation]

/v3/research-products/links: relations between research products.

This route has no cursor and no sort parameter. Page windows are therefore not pinned: if the result ordering changes between requests, pages can shift and relations can be skipped or duplicated. The iterator stops on an empty page or when the reported total has been fetched, which bounds the walk but cannot remove that upstream hazard.

Source code in packages/aireloom/src/aireloom/_async/resources.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
class LinksResource(ResourceClient[Relation]):
    """``/v3/research-products/links``: relations between research products.

    This route has no cursor and no sort parameter. Page windows are therefore
    not pinned: if the result ordering changes between requests, pages can
    shift and relations can be skipped or duplicated. The iterator stops on an
    empty page or when the reported total has been fetched, which bounds the
    walk but cannot remove that upstream hazard.
    """

    path = "v3/research-products/links"
    model = Relation
    dialect = LINKS_DIALECT
    filters_model = LinksFilters
    batch_size = 0

    async def get_relations_info(self) -> list[RelationInfo]:
        """Return the relation types the links endpoint can produce."""
        response = await self._client.request("GET", f"{self.path}/relations-info")
        payload = self._client.parse_json(response)
        if not isinstance(payload, list):
            raise ValidationError(
                "Expected a JSON list from relations-info.",
                raw=payload,
                error=TypeError(f"Expected list, got {type(payload).__name__}"),
                model_name=RelationInfo.__name__,
                request=response.request,
                response=response,
            )
        return [
            validate_model(
                RelationInfo, entry, request=response.request, response=response
            )
            for entry in payload
        ]

get_relations_info() async

Return the relation types the links endpoint can produce.

Source code in packages/aireloom/src/aireloom/_async/resources.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
async def get_relations_info(self) -> list[RelationInfo]:
    """Return the relation types the links endpoint can produce."""
    response = await self._client.request("GET", f"{self.path}/relations-info")
    payload = self._client.parse_json(response)
    if not isinstance(payload, list):
        raise ValidationError(
            "Expected a JSON list from relations-info.",
            raw=payload,
            error=TypeError(f"Expected list, got {type(payload).__name__}"),
            model_name=RelationInfo.__name__,
            request=response.request,
            response=response,
        )
    return [
        validate_model(
            RelationInfo, entry, request=response.request, response=response
        )
        for entry in payload
    ]

aireloom.ScholixResource

Scholix link search over the Scholexplorer host (V3 default, V2 fallback).

Backed by a dedicated internal API client for api.scholexplorer.openaire.eu that shares the Graph client's credentials and settings but throttles itself to one request per second (the host sends no rate-limit headers).

V3 is the default surface. Queries carrying linkProvider are routed to V2 because V3 silently ignores linkProvider. Queries carrying from_date or to_date raise :class:ConfigurationError because V3 returns zero rows for date filters and V2 silently ignores date parameters.

Source code in packages/aireloom/src/aireloom/_async/resources.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
class ScholixResource:
    """Scholix link search over the Scholexplorer host (V3 default, V2 fallback).

    Backed by a dedicated internal API client for ``api.scholexplorer.openaire.eu``
    that shares the Graph client's credentials and settings but throttles
    itself to one request per second (the host sends no rate-limit headers).

    V3 is the default surface. Queries carrying ``linkProvider`` are routed to
    V2 because V3 silently ignores ``linkProvider``. Queries carrying
    ``from_date`` or ``to_date`` raise :class:`ConfigurationError` because V3
    returns zero rows for date filters and V2 silently ignores date parameters.
    """

    def __init__(self, client: BaseApiClient) -> None:
        self._v3 = ScholixV3Links(client)
        self._v2 = ScholixV2Links(client)
        self._client = client

    @staticmethod
    def _has_date_filter(filters: ScholixFilters | Mapping[str, Any] | None) -> bool:
        if filters is None:
            return False
        if isinstance(filters, ScholixFilters):
            return filters.from_date is not None or filters.to_date is not None
        return any(
            filters.get(key) is not None
            for key in ("from", "to", "from_date", "to_date")
        )

    @classmethod
    def _reject_date_filter(
        cls, filters: ScholixFilters | Mapping[str, Any] | None
    ) -> None:
        if cls._has_date_filter(filters):
            raise ConfigurationError(
                "Scholexplorer does not support 'from_date'/'to_date' filtering "
                "(V3 returns zero rows for 'from'/'to' and V2 silently ignores "
                "date parameters). Remove 'from_date'/'to_date' from filters and "
                "filter results by 'link_publication_date' client-side, or query "
                "Graph V4 research products with 'from_publication_date' / "
                "'to_publication_date'."
            )

    @staticmethod
    def _has_link_provider(filters: ScholixFilters | Mapping[str, Any] | None) -> bool:
        if filters is None:
            return False
        if isinstance(filters, ScholixFilters):
            return filters.linkProvider is not None
        return filters.get("linkProvider") is not None

    def _select_target(
        self, filters: ScholixFilters | Mapping[str, Any] | None
    ) -> _ScholixLinks:
        self._reject_date_filter(filters)
        if self._has_link_provider(filters):
            return self._v2
        return self._v3

    async def search_links(
        self,
        filters: ScholixFilters | Mapping[str, Any] | None = None,
        *,
        page: int | None = None,
        page_size: int | None = None,
    ) -> Page[ScholixRelationship]:
        """Fetch one page of links as typed records.

        Queries with ``linkProvider`` route to V2 (V3 silently ignores it);
        everything else goes to V3. Passing ``from_date`` or ``to_date`` raises
        :class:`ConfigurationError`.
        """
        target = self._select_target(filters)
        return await target.search(filters, page=page, page_size=page_size)

    def iterate_links(
        self,
        filters: ScholixFilters | Mapping[str, Any] | None = None,
        *,
        page_size: int | None = None,
        limit: int | None = None,
        on_error: OnError = "raise",
        failures: list[tuple[dict[str, Any], Exception]] | None = None,
        on_page: Callable[[int, str | None], Any] | None = None,
    ) -> AsyncIterator[ScholixRelationship]:
        """Iterate over all matching links, 99 per page.

        See :meth:`search_links` for V2/V3 routing rules and date-filter
        rejection. The route has no cursor, so page windows are not pinned; the
        iterator stops on an empty page or when the reported total has been
        fetched.
        """
        target = self._select_target(filters)
        return target.iterate(
            filters,
            page_size=page_size,
            limit=limit,
            on_error=on_error,
            failures=failures,
            on_page=on_page,
        )

    async def search_links_v2(
        self,
        filters: ScholixFilters | Mapping[str, Any] | None = None,
        *,
        page: int | None = None,
        page_size: int | None = None,
    ) -> Page[ScholixRelationship]:
        """Fetch one page of links from the V2 endpoint.

        Passing ``from_date`` or ``to_date`` raises :class:`ConfigurationError`
        because V2 silently ignores date parameters.
        """
        self._reject_date_filter(filters)
        return await self._v2.search(filters, page=page, page_size=page_size)

    def iterate_links_v2(
        self,
        filters: ScholixFilters | Mapping[str, Any] | None = None,
        *,
        page_size: int | None = None,
        limit: int | None = None,
        on_error: OnError = "raise",
        failures: list[tuple[dict[str, Any], Exception]] | None = None,
        on_page: Callable[[int, str | None], Any] | None = None,
    ) -> AsyncIterator[ScholixRelationship]:
        """Iterate over all matching links from the V2 endpoint.

        Passing ``from_date`` or ``to_date`` raises :class:`ConfigurationError`
        because V2 silently ignores date parameters.
        """
        self._reject_date_filter(filters)
        return self._v2.iterate(
            filters,
            page_size=page_size,
            limit=limit,
            on_error=on_error,
            failures=failures,
            on_page=on_page,
        )

    async def list_link_providers(
        self, name: str | None = None
    ) -> list[ScholixLinkProvider]:
        """List Scholexplorer link providers (V2)."""
        params = {"name": name} if name is not None else None
        response = await self._client.request("GET", "v2/LinkProvider", params=params)
        payload = self._client.parse_json(response)
        return [
            validate_model(
                ScholixLinkProvider, entry, request=response.request, response=response
            )
            for entry in _records(payload)
        ]

    async def list_link_publishers(
        self, *, in_target: bool = True, name: str | None = None
    ) -> list[ScholixPublisher]:
        """List publishers of source or target objects (V2)."""
        path = "v2/LinkPublisher/inTarget" if in_target else "v2/LinkPublisher/inSource"
        params = {"name": name} if name is not None else None
        response = await self._client.request("GET", path, params=params)
        payload = self._client.parse_json(response)
        return [
            validate_model(
                ScholixPublisher, entry, request=response.request, response=response
            )
            for entry in _records(payload)
        ]

    async def get_kpi(self) -> str:
        """Return the Scholexplorer Prometheus KPI document."""
        response = await self._client.request("GET", "kpi/getKPI")
        return response.text

get_kpi() async

Return the Scholexplorer Prometheus KPI document.

Source code in packages/aireloom/src/aireloom/_async/resources.py
707
708
709
710
async def get_kpi(self) -> str:
    """Return the Scholexplorer Prometheus KPI document."""
    response = await self._client.request("GET", "kpi/getKPI")
    return response.text

Iterate over all matching links, 99 per page.

See :meth:search_links for V2/V3 routing rules and date-filter rejection. The route has no cursor, so page windows are not pinned; the iterator stops on an empty page or when the reported total has been fetched.

Source code in packages/aireloom/src/aireloom/_async/resources.py
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
def iterate_links(
    self,
    filters: ScholixFilters | Mapping[str, Any] | None = None,
    *,
    page_size: int | None = None,
    limit: int | None = None,
    on_error: OnError = "raise",
    failures: list[tuple[dict[str, Any], Exception]] | None = None,
    on_page: Callable[[int, str | None], Any] | None = None,
) -> AsyncIterator[ScholixRelationship]:
    """Iterate over all matching links, 99 per page.

    See :meth:`search_links` for V2/V3 routing rules and date-filter
    rejection. The route has no cursor, so page windows are not pinned; the
    iterator stops on an empty page or when the reported total has been
    fetched.
    """
    target = self._select_target(filters)
    return target.iterate(
        filters,
        page_size=page_size,
        limit=limit,
        on_error=on_error,
        failures=failures,
        on_page=on_page,
    )

Iterate over all matching links from the V2 endpoint.

Passing from_date or to_date raises :class:ConfigurationError because V2 silently ignores date parameters.

Source code in packages/aireloom/src/aireloom/_async/resources.py
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
def iterate_links_v2(
    self,
    filters: ScholixFilters | Mapping[str, Any] | None = None,
    *,
    page_size: int | None = None,
    limit: int | None = None,
    on_error: OnError = "raise",
    failures: list[tuple[dict[str, Any], Exception]] | None = None,
    on_page: Callable[[int, str | None], Any] | None = None,
) -> AsyncIterator[ScholixRelationship]:
    """Iterate over all matching links from the V2 endpoint.

    Passing ``from_date`` or ``to_date`` raises :class:`ConfigurationError`
    because V2 silently ignores date parameters.
    """
    self._reject_date_filter(filters)
    return self._v2.iterate(
        filters,
        page_size=page_size,
        limit=limit,
        on_error=on_error,
        failures=failures,
        on_page=on_page,
    )

List Scholexplorer link providers (V2).

Source code in packages/aireloom/src/aireloom/_async/resources.py
678
679
680
681
682
683
684
685
686
687
688
689
690
async def list_link_providers(
    self, name: str | None = None
) -> list[ScholixLinkProvider]:
    """List Scholexplorer link providers (V2)."""
    params = {"name": name} if name is not None else None
    response = await self._client.request("GET", "v2/LinkProvider", params=params)
    payload = self._client.parse_json(response)
    return [
        validate_model(
            ScholixLinkProvider, entry, request=response.request, response=response
        )
        for entry in _records(payload)
    ]

List publishers of source or target objects (V2).

Source code in packages/aireloom/src/aireloom/_async/resources.py
692
693
694
695
696
697
698
699
700
701
702
703
704
705
async def list_link_publishers(
    self, *, in_target: bool = True, name: str | None = None
) -> list[ScholixPublisher]:
    """List publishers of source or target objects (V2)."""
    path = "v2/LinkPublisher/inTarget" if in_target else "v2/LinkPublisher/inSource"
    params = {"name": name} if name is not None else None
    response = await self._client.request("GET", path, params=params)
    payload = self._client.parse_json(response)
    return [
        validate_model(
            ScholixPublisher, entry, request=response.request, response=response
        )
        for entry in _records(payload)
    ]

Fetch one page of links as typed records.

Queries with linkProvider route to V2 (V3 silently ignores it); everything else goes to V3. Passing from_date or to_date raises :class:ConfigurationError.

Source code in packages/aireloom/src/aireloom/_async/resources.py
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
async def search_links(
    self,
    filters: ScholixFilters | Mapping[str, Any] | None = None,
    *,
    page: int | None = None,
    page_size: int | None = None,
) -> Page[ScholixRelationship]:
    """Fetch one page of links as typed records.

    Queries with ``linkProvider`` route to V2 (V3 silently ignores it);
    everything else goes to V3. Passing ``from_date`` or ``to_date`` raises
    :class:`ConfigurationError`.
    """
    target = self._select_target(filters)
    return await target.search(filters, page=page, page_size=page_size)

Fetch one page of links from the V2 endpoint.

Passing from_date or to_date raises :class:ConfigurationError because V2 silently ignores date parameters.

Source code in packages/aireloom/src/aireloom/_async/resources.py
638
639
640
641
642
643
644
645
646
647
648
649
650
651
async def search_links_v2(
    self,
    filters: ScholixFilters | Mapping[str, Any] | None = None,
    *,
    page: int | None = None,
    page_size: int | None = None,
) -> Page[ScholixRelationship]:
    """Fetch one page of links from the V2 endpoint.

    Passing ``from_date`` or ``to_date`` raises :class:`ConfigurationError`
    because V2 silently ignores date parameters.
    """
    self._reject_date_filter(filters)
    return await self._v2.search(filters, page=page, page_size=page_size)

Sync client

The sync twins mirror the async classes above; they take the same parameters and raise the same errors. See Sync usage.

aireloom.AireloomSyncClient

Bases: SyncBaseApiClient

Client for the OpenAIRE Graph API (V4) and the Scholexplorer API.

Entity resources are available as typed attributes; single-entity lookups go through the V3 by-id routes because V4 has none. Authentication resolves in the constructor: set openaire_refresh_token / refresh_token for OAuth2 refresh-token access, or set both openaire_client_id and openaire_client_secret (settings, AIRELOOM_OPENAIRE_CLIENT_ID / AIRELOOM_OPENAIRE_CLIENT_SECRET, or client_id / client_secret) for OAuth2 client-credentials access against the Keycloak token endpoint; partial client credentials raise :class:ConfigurationError, and without credentials the client is anonymous. An explicit auth_strategy always wins.

The Scholix resource talks to the Scholexplorer host through a second internal client that shares settings and credentials but throttles itself to one request per second. See the package README and docs for usage examples of both the async and the sync variants.

Source code in packages/aireloom/src/aireloom/_sync/client.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
class AireloomSyncClient(SyncBaseApiClient):
    """Client for the OpenAIRE Graph API (V4) and the Scholexplorer API.

    Entity resources are available as typed attributes; single-entity lookups
    go through the V3 by-id routes because V4 has none. Authentication
    resolves in the constructor: set ``openaire_refresh_token`` /
    ``refresh_token`` for OAuth2 refresh-token access, or set both
    ``openaire_client_id`` and ``openaire_client_secret`` (settings,
    ``AIRELOOM_OPENAIRE_CLIENT_ID`` / ``AIRELOOM_OPENAIRE_CLIENT_SECRET``, or
    ``client_id`` / ``client_secret``) for OAuth2 client-credentials access
    against the Keycloak token endpoint; partial client credentials raise
    :class:`ConfigurationError`, and without credentials the client is
    anonymous. An explicit ``auth_strategy`` always wins.

    The Scholix resource talks to the Scholexplorer host through a second
    internal client that shares settings and credentials but throttles itself
    to one request per second. See the package README and docs for usage
    examples of both the async and the sync variants.
    """

    def __init__(
        self,
        settings: AireloomSettings | None = None,
        auth: AuthStrategy | None = None,
        *,
        auth_strategy: AuthStrategy | None = None,
        base_url: str | None = None,
        scholix_base_url: str | None = None,
        mailto: str | None = None,
        client_id: str | None = None,
        client_secret: str | None = None,
        refresh_token: str | None = None,
        http_client: httpx.Client | None = None,
    ) -> None:
        """Build the client from settings, resolving credentials immediately.

        ``settings`` defaults to :func:`aireloom.config.get_settings`, which
        reads ``AIRELOOM_*`` environment variables and ``.env``. Keyword
        overrides (``base_url``, ``scholix_base_url``, ``mailto``,
        ``client_id``, ``client_secret``, ``refresh_token``) take precedence
        over ``settings``. Pass ``auth_strategy`` for a custom auth strategy
        (``auth`` is a deprecated alias).
        """
        if auth is not None and auth_strategy is not None:
            raise ConfigurationError(
                "Pass either 'auth_strategy' or the deprecated 'auth' parameter, "
                "not both."
            )
        if auth is not None:
            warnings.warn(
                "The 'auth' parameter is deprecated; use 'auth_strategy' instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            explicit_auth: AuthStrategy | None = auth
        else:
            explicit_auth = auth_strategy

        resolved = settings or get_settings()
        overrides: dict[str, str] = {}
        if base_url is not None:
            overrides["base_url"] = base_url
        if scholix_base_url is not None:
            overrides["scholix_base_url"] = scholix_base_url
        if mailto is not None:
            overrides["mailto"] = mailto
        if client_id is not None:
            overrides["openaire_client_id"] = client_id
        if client_secret is not None:
            overrides["openaire_client_secret"] = client_secret
        if refresh_token is not None:
            overrides["openaire_refresh_token"] = refresh_token
        if overrides:
            resolved = resolved.model_copy(update=overrides)
        strategy = (
            explicit_auth if explicit_auth is not None else _resolve_auth(resolved)
        )
        super().__init__(
            base_url=resolved.base_url,
            settings=resolved,
            unwrapper=OpenAireUnwrapper(),
            auth=strategy,
            http_client=http_client,
        )
        self._scholix_api = SyncBaseApiClient(
            base_url=resolved.scholix_base_url,
            settings=resolved.model_copy(
                update={
                    "max_requests_per_second": resolved.scholix_max_requests_per_second
                }
            ),
            unwrapper=ScholixUnwrapper(),
            auth=strategy,
        )
        auth_label = (
            "anonymous" if isinstance(strategy, NoAuth) else type(strategy).__name__
        )
        logger.debug("%s initialized (%s).", type(self).__name__, auth_label)

    def request(
        self,
        method: str,
        path: str,
        *,
        params: Mapping[str, Any] | None = None,
        json: Any | None = None,
        data: Mapping[str, Any] | None = None,
        content: str | bytes | None = None,
        headers: Mapping[str, str] | None = None,
        timeout: float | httpx.Timeout | None = None,
        retry: bool | None = None,
        follow_redirects: bool | None = None,
    ) -> httpx.Response:
        """Send a request through the core retry pipeline.

        V4 accepts ``mailto`` for polite-pool admission (V3 rejects it), so the
        configured contact address is attached to ``v4/`` requests only.
        """
        effective_params: Mapping[str, Any] | None = params
        if path.lstrip("/").startswith("v4/") and self._settings.mailto:
            if params is None:
                effective_params = {"mailto": self._settings.mailto}
            elif isinstance(params, Mapping):
                if "mailto" not in params:
                    effective_params = {"mailto": self._settings.mailto, **params}
            else:
                qp = httpx.QueryParams(params)
                if "mailto" not in qp:
                    effective_params = qp.set("mailto", self._settings.mailto)
        return super().request(
            method,
            path,
            params=effective_params,
            json=json,
            data=data,
            content=content,
            headers=headers,
            timeout=timeout,
            retry=retry,
            follow_redirects=follow_redirects,
        )

    @functools.cached_property
    def _links(self) -> SyncLinksResource:
        return SyncLinksResource(self)

    @functools.cached_property
    def research_products(self) -> SyncResearchProductsResource:
        """Search, iterate, and batch-fetch research products; links helpers."""
        return SyncResearchProductsResource(self, self._links)

    @functools.cached_property
    def projects(self) -> SyncProjectsResource:
        """Search and iterate OpenAIRE projects."""
        return SyncProjectsResource(self)

    @functools.cached_property
    def organizations(self) -> SyncOrganizationsResource:
        """Search and iterate OpenAIRE organizations."""
        return SyncOrganizationsResource(self)

    @functools.cached_property
    def data_sources(self) -> SyncDataSourcesResource:
        """Search and iterate OpenAIRE data sources."""
        return SyncDataSourcesResource(self)

    @functools.cached_property
    def persons(self) -> SyncPersonsResource:
        """Search and iterate OpenAIRE persons."""
        return SyncPersonsResource(self)

    @functools.cached_property
    def scholix(self) -> SyncScholixResource:
        """Search Scholix links on the Scholexplorer host (V3, V2 for linkProvider)."""
        return SyncScholixResource(self._scholix_api)

    def close(self) -> None:
        """Close both the Graph and the Scholix HTTP clients."""
        try:
            super().close()
        finally:
            self._scholix_api.close()

request(method, path, *, params=None, json=None, data=None, content=None, headers=None, timeout=None, retry=None, follow_redirects=None)

Send a request through the core retry pipeline.

V4 accepts mailto for polite-pool admission (V3 rejects it), so the configured contact address is attached to v4/ requests only.

Source code in packages/aireloom/src/aireloom/_sync/client.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def request(
    self,
    method: str,
    path: str,
    *,
    params: Mapping[str, Any] | None = None,
    json: Any | None = None,
    data: Mapping[str, Any] | None = None,
    content: str | bytes | None = None,
    headers: Mapping[str, str] | None = None,
    timeout: float | httpx.Timeout | None = None,
    retry: bool | None = None,
    follow_redirects: bool | None = None,
) -> httpx.Response:
    """Send a request through the core retry pipeline.

    V4 accepts ``mailto`` for polite-pool admission (V3 rejects it), so the
    configured contact address is attached to ``v4/`` requests only.
    """
    effective_params: Mapping[str, Any] | None = params
    if path.lstrip("/").startswith("v4/") and self._settings.mailto:
        if params is None:
            effective_params = {"mailto": self._settings.mailto}
        elif isinstance(params, Mapping):
            if "mailto" not in params:
                effective_params = {"mailto": self._settings.mailto, **params}
        else:
            qp = httpx.QueryParams(params)
            if "mailto" not in qp:
                effective_params = qp.set("mailto", self._settings.mailto)
    return super().request(
        method,
        path,
        params=effective_params,
        json=json,
        data=data,
        content=content,
        headers=headers,
        timeout=timeout,
        retry=retry,
        follow_redirects=follow_redirects,
    )

close()

Close both the Graph and the Scholix HTTP clients.

Source code in packages/aireloom/src/aireloom/_sync/client.py
236
237
238
239
240
241
def close(self) -> None:
    """Close both the Graph and the Scholix HTTP clients."""
    try:
        super().close()
    finally:
        self._scholix_api.close()

Filter models

aireloom.ResearchProductsFilters

Bases: GraphFilters

V4 filters for /v4/research-products.

Value strings may carry the operators the API accepts: a leading ! negates, >/< compare on date and numeric fields such as impact_citation_count, sequences join with | for OR within a field (up to 50 values), and from_/to_ pairs bound ranges.

Source code in packages/aireloom/src/aireloom/filters.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class ResearchProductsFilters(GraphFilters):
    """V4 filters for ``/v4/research-products``.

    Value strings may carry the operators the API accepts: a leading ``!``
    negates, ``>``/``<`` compare on date and numeric fields such as
    ``impact_citation_count``, sequences join with ``|`` for OR within a field
    (up to 50 values), and ``from_``/``to_`` pairs bound ranges.
    """

    id: StrFilter | None = None
    ids_doi: StrFilter | None = Field(default=None, alias="ids.doi")
    ids_pmid: StrFilter | None = Field(default=None, alias="ids.pmid")
    ids_pmcid: StrFilter | None = Field(default=None, alias="ids.pmcid")
    ids_arxiv: StrFilter | None = Field(default=None, alias="ids.arxiv")
    ids_handle: StrFilter | None = Field(default=None, alias="ids.handle")
    ids_original: StrFilter | None = Field(default=None, alias="ids.original")
    ids_pid: StrFilter | None = Field(default=None, alias="ids.pid")
    type: V4_ENTITY_TYPES | str | Sequence[str] | None = None
    instance_type: StrFilter | None = None
    subjects: StrFilter | None = None
    sdg: StrFilter | None = None
    fos: StrFilter | None = None
    from_publication_date: DateFilter | None = None
    to_publication_date: DateFilter | None = None
    from_publication_year: int | None = None
    to_publication_year: int | None = None
    date_of_collection: DateFilter | None = None
    title_search: str | None = Field(default=None, alias="title.search")
    abstract_search: str | None = Field(default=None, alias="abstract.search")
    title_and_abstract_search: str | None = Field(
        default=None, alias="title_and_abstract.search"
    )
    default_search: str | None = Field(default=None, alias="default.search")
    authorships_author_fullname: StrFilter | None = Field(
        default=None, alias="authorships.author.fullname"
    )
    authorships_author_orcid: StrFilter | None = Field(
        default=None, alias="authorships.author.orcid"
    )
    authorships_institutions_ror: StrFilter | None = Field(
        default=None, alias="authorships.institutions.ror"
    )
    authorships_countries: StrFilter | None = Field(
        default=None, alias="authorships.countries"
    )
    authorships_continent: StrFilter | None = Field(
        default=None, alias="authorships.continent"
    )
    authorships_is_global_south: bool | None = Field(
        default=None, alias="authorships.is_global_south"
    )
    has_doi: bool | None = None
    has_pmid: bool | None = None
    has_pmcid: bool | None = None
    has_arxiv: bool | None = None
    has_handle: bool | None = None
    has_orcid: bool | None = None
    has_abstract: bool | None = None
    has_grant: bool | None = None
    has_license: bool | None = None
    best_oa_rights: StrFilter | None = Field(default=None, alias="best_oa.rights")
    oa_color: StrFilter | None = None
    is_green: bool | None = None
    is_peer_reviewed: bool | None = None
    is_in_diamond_journal: bool | None = None
    is_publicly_funded: bool | None = None
    impact_influence_class: StrFilter | None = Field(
        default=None, alias="impact.influence_class"
    )
    impact_popularity_class: StrFilter | None = Field(
        default=None, alias="impact.popularity_class"
    )
    impact_impulse_class: StrFilter | None = Field(
        default=None, alias="impact.impulse_class"
    )
    impact_citation_count_class: StrFilter | None = Field(
        default=None, alias="impact.citation_count_class"
    )
    impact_citation_count: int | str | None = Field(
        default=None, alias="impact.citation_count"
    )
    publisher: StrFilter | None = None
    host_datasource_id: StrFilter | None = Field(
        default=None, alias="host_datasource.id"
    )
    collected_from_id: StrFilter | None = Field(default=None, alias="collected_from.id")
    grants_project_id: StrFilter | None = Field(default=None, alias="grants.project_id")
    grants_code: StrFilter | None = Field(default=None, alias="grants.code")
    grants_funder_short_name: StrFilter | None = Field(
        default=None, alias="grants.funder_short_name"
    )
    grants_funding_stream_id: StrFilter | None = Field(
        default=None, alias="grants.funding_stream_id"
    )
    affiliations_organization_id: StrFilter | None = Field(
        default=None, alias="affiliations.organization_id"
    )
    communities_id: StrFilter | None = Field(default=None, alias="communities.id")
    language: StrFilter | None = None

aireloom.ProjectsFilters

Bases: GraphFilters

V4 filters for /v4/projects.

Source code in packages/aireloom/src/aireloom/filters.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
class ProjectsFilters(GraphFilters):
    """V4 filters for ``/v4/projects``."""

    id: StrFilter | None = None
    code: StrFilter | None = None
    acronym: StrFilter | None = None
    pid: StrFilter | None = None
    call_identifier: StrFilter | None = None
    project_status: V4_PROJECT_STATUS | str | Sequence[str] | None = None
    title_search: str | None = Field(default=None, alias="title.search")
    keywords_search: str | None = Field(default=None, alias="keywords.search")
    default_search: str | None = Field(default=None, alias="default.search")
    funder: StrFilter | None = None
    funder_short_name: StrFilter | None = None
    funding_stream_id: StrFilter | None = None
    funding_level_0_id: StrFilter | None = None
    funding_level_1_id: StrFilter | None = None
    funding_level_2_id: StrFilter | None = None
    country: StrFilter | None = None
    continent: StrFilter | None = None
    is_global_south: bool | None = None
    oa_mandate_publications: bool | None = None
    from_start_date: DateFilter | None = None
    to_start_date: DateFilter | None = None
    from_end_date: DateFilter | None = None
    to_end_date: DateFilter | None = None
    start_year: NumericFilter | None = None
    end_year: NumericFilter | None = None
    active_year: NumericFilter | None = None
    organizations_id: StrFilter | None = Field(default=None, alias="organizations.id")
    organizations_name: StrFilter | None = Field(
        default=None, alias="organizations.name"
    )
    organizations_country: StrFilter | None = Field(
        default=None, alias="organizations.country"
    )
    communities_id: StrFilter | None = Field(default=None, alias="communities.id")
    collected_from_id: StrFilter | None = Field(default=None, alias="collected_from.id")

aireloom.OrganizationsFilters

Bases: GraphFilters

V4 filters for /v4/organizations.

Source code in packages/aireloom/src/aireloom/filters.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
class OrganizationsFilters(GraphFilters):
    """V4 filters for ``/v4/organizations``."""

    id: StrFilter | None = None
    pid: StrFilter | None = None
    legal_name_search: str | None = Field(default=None, alias="legal_name.search")
    legal_short_name_search: str | None = Field(
        default=None, alias="legal_short_name.search"
    )
    default_search: str | None = Field(default=None, alias="default.search")
    country: StrFilter | None = None
    continent: StrFilter | None = None
    is_global_south: bool | None = None
    communities_id: StrFilter | None = Field(default=None, alias="communities.id")
    collected_from_id: StrFilter | None = Field(default=None, alias="collected_from.id")

aireloom.DataSourcesFilters

Bases: GraphFilters

V4 filters for /v4/datasources.

Source code in packages/aireloom/src/aireloom/filters.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
class DataSourcesFilters(GraphFilters):
    """V4 filters for ``/v4/datasources``."""

    id: StrFilter | None = None
    pid: StrFilter | None = None
    official_name_search: str | None = Field(default=None, alias="official_name.search")
    english_name_search: str | None = Field(default=None, alias="english_name.search")
    default_search: str | None = Field(default=None, alias="default.search")
    type: StrFilter | None = None
    subjects: StrFilter | None = None
    content_types: StrFilter | None = None
    eosc_datasource_type: StrFilter | None = None
    jurisdiction: StrFilter | None = None
    thematic: bool | None = None
    od_languages: StrFilter | None = None
    country: StrFilter | None = None
    continent: StrFilter | None = None
    is_global_south: bool | None = None
    compatibility_id: StrFilter | None = Field(default=None, alias="compatibility.id")
    compatibility_name: StrFilter | None = Field(
        default=None, alias="compatibility.name"
    )
    organizations_id: StrFilter | None = Field(default=None, alias="organizations.id")
    communities_id: StrFilter | None = Field(default=None, alias="communities.id")
    collected_from_id: StrFilter | None = Field(default=None, alias="collected_from.id")
    collected_from_name: StrFilter | None = Field(
        default=None, alias="collected_from.name"
    )

aireloom.PersonsFilters

Bases: GraphFilters

V4 filters for /v4/persons.

Source code in packages/aireloom/src/aireloom/filters.py
284
285
286
287
288
289
290
291
class PersonsFilters(GraphFilters):
    """V4 filters for ``/v4/persons``."""

    id: StrFilter | None = None
    ids_original: StrFilter | None = Field(default=None, alias="ids.original")
    given_name: StrFilter | None = None
    last_name: StrFilter | None = None
    default_search: str | None = Field(default=None, alias="default.search")

aireloom.LinksFilters

Bases: BaseModel

Query parameters for the Graph /v3/research-products/links route.

This route takes individual parameters (not the V4 filter expression), so each attribute maps to one query parameter.

Source code in packages/aireloom/src/aireloom/filters.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
class LinksFilters(BaseModel):
    """Query parameters for the Graph ``/v3/research-products/links`` route.

    This route takes individual parameters (not the V4 filter expression), so
    each attribute maps to one query parameter.
    """

    model_config = ConfigDict(extra="forbid")

    sourcePid: str | None = Field(
        default=None, description="Source persistent identifier, e.g. a DOI"
    )
    targetPid: str | None = Field(
        default=None, description="Target persistent identifier"
    )
    sourcePublisher: str | None = Field(
        default=None, description="Source publisher name"
    )
    targetPublisher: str | None = Field(
        default=None, description="Target publisher name"
    )
    sourceType: V4_ENTITY_TYPES | None = None
    targetType: V4_ENTITY_TYPES | None = None
    relation: str | None = Field(
        default=None, description="Relationship type, e.g. IsSupplementTo"
    )
    fromDate: DateFilter | None = Field(default=None, description="YYYY or YYYY-MM-DD")
    toDate: DateFilter | None = Field(default=None, description="YYYY or YYYY-MM-DD")

aireloom.ScholixFilters

Bases: BaseModel

Query parameters for the Scholexplorer Links endpoints (V3 and V2).

One of sourcePid, targetPid, sourcePublisher, targetPublisher, sourceType, or targetType is required. linkProvider is supported on V2 only (V3 silently ignores it), so queries carrying linkProvider are routed to V2 automatically. from_date/to_date are rejected by :class:ScholixResource with :class:ConfigurationError because V3 returns zero rows for them and V2 silently ignores them (see docs/aireloom/quirks.md).

Source code in packages/aireloom/src/aireloom/filters.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
class ScholixFilters(BaseModel):
    """Query parameters for the Scholexplorer ``Links`` endpoints (V3 and V2).

    One of ``sourcePid``, ``targetPid``, ``sourcePublisher``,
    ``targetPublisher``, ``sourceType``, or ``targetType`` is required.
    ``linkProvider`` is supported on V2 only (V3 silently ignores it), so
    queries carrying ``linkProvider`` are routed to V2 automatically.
    ``from_date``/``to_date`` are rejected by :class:`ScholixResource` with
    :class:`ConfigurationError` because V3 returns zero rows for them and V2
    silently ignores them (see ``docs/aireloom/quirks.md``).
    """

    model_config = ConfigDict(extra="forbid", populate_by_name=True)

    sourcePid: str | None = None
    targetPid: str | None = None
    sourcePublisher: str | None = None
    targetPublisher: str | None = None
    sourceType: Literal["Publication", "Dataset", "Software", "Other"] | None = None
    targetType: Literal["Publication", "Dataset", "Software", "Other"] | None = None
    relation: str | None = None
    linkProvider: str | None = None
    from_date: DateFilter | None = Field(
        default=None, alias="from", description="YYYY or YYYY-MM-DD"
    )
    to_date: DateFilter | None = Field(
        default=None, alias="to", description="YYYY or YYYY-MM-DD"
    )

Paging

iterate() yields Page records. The model is documented in the bibliofabric paging reference.

Models

aireloom.ResearchProduct

Bases: BaseEntity

Model representing an OpenAIRE Research Product entity.

Covers the V3/V4 response surface (47 keys observed live): titles, authors, access rights, countries, subjects, indicators, instances, Open Access flags, subtype-specific fields, and typed relationship lists. Inherits id from BaseEntity.

Source code in packages/aireloom/src/aireloom/models/research_product.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
class ResearchProduct(BaseEntity):
    """Model representing an OpenAIRE Research Product entity.

    Covers the V3/V4 response surface (47 keys observed live): titles, authors,
    access rights, countries, subjects, indicators, instances, Open Access
    flags, subtype-specific fields, and typed relationship lists. Inherits
    ``id`` from ``BaseEntity``.
    """

    originalIds: SafeList[str] = Field(default_factory=list)
    pids: SafeList[Pid] = Field(default_factory=list)
    type: ResearchProductType | None = None
    mainTitle: SafeStr = ""
    subTitle: SafeStr = ""
    otherTitles: SafeList[str] = Field(default_factory=list)
    authors: SafeList[Author] = Field(default_factory=list)
    bestAccessRight: SafeBestAccessRight = Field(default_factory=BestAccessRight)
    countries: SafeList[CodeLabel] = Field(default_factory=list)
    descriptions: SafeList[str] = Field(default_factory=list)
    publicationDate: str | None = None
    publisher: SafeStr = ""
    embargoEndDate: str | None = None
    contributors: SafeList[str] = Field(default_factory=list)
    sources: SafeList[str] = Field(default_factory=list)
    formats: SafeList[str] = Field(default_factory=list)
    coverages: SafeList[str] = Field(default_factory=list)
    dateOfCollection: str | None = None
    lastUpdateTimeStamp: int | None = None
    indicators: SafeIndicator = Field(default_factory=Indicator)
    instances: SafeList[Instance] = Field(default_factory=list)
    language: SafeLanguage = Field(default_factory=Language)
    subjects: SafeList[Subject] = Field(default_factory=list)
    container: SafeContainer = Field(default_factory=Container)
    geoLocations: SafeList[GeoLocation] = Field(default_factory=list)

    # Open Access fields
    isGreen: bool | None = None
    green: bool | None = None
    isInDiamondJournal: bool | None = None
    inDiamondJournal: bool | None = None
    openAccessColor: str | None = None
    publiclyFunded: bool | None = None
    eoscIfGuidelines: SafeList[EoscIfGuideline] = Field(default_factory=list)

    # Subtype-specific fields (Software)
    codeRepositoryUrl: str | None = None
    documentationUrls: SafeList[str] = Field(default_factory=list)
    programmingLanguage: str | None = None

    # Subtype-specific fields (Dataset)
    size: str | None = None
    version: str | None = None

    # Subtype-specific fields (Other)
    contactPeople: SafeList[str] = Field(default_factory=list)
    contactGroups: SafeList[str] = Field(default_factory=list)
    tools: SafeList[str] = Field(default_factory=list)

    # Relationship fields
    collectedFrom: SafeList[CfHbKeyValue] = Field(default_factory=list)
    projects: SafeList[ProductProject] = Field(default_factory=list)
    organizations: SafeList[ProductOrganization] = Field(default_factory=list)
    communities: SafeList[ProductCommunity] = Field(default_factory=list)
    links: SafeList[RelatedRecord] = Field(default_factory=list)

    # ── Computed fields ─────────────────────────────────────────────────

    @computed_field
    @property
    def doi(self) -> str | None:
        """First DOI from the pids list."""
        return extract_pid_by_scheme(self.pids, "doi")

    @computed_field
    @property
    def all_dois(self) -> list[str]:
        """All DOI values from the pids list."""
        return extract_all_pids_by_scheme(self.pids, "doi")

    @computed_field
    @property
    def is_open_access(self) -> bool:
        """True when the best access right is OPEN."""
        return self.bestAccessRight.label.upper() == "OPEN"

    @computed_field
    @property
    def open_access_url(self) -> str | None:
        """URL of the first instance whose access right is OPEN."""
        for inst in self.instances:
            if (
                inst.accessRight
                and inst.accessRight.label
                and inst.accessRight.label.upper() == "OPEN"
                and inst.urls
            ):
                return inst.urls[0]
        return None

    @computed_field
    @property
    def citation_count(self) -> int | None:
        """Citation count from indicators, if available."""
        return self.indicators.citationImpact.citationCount

    @computed_field
    @property
    def publication_year(self) -> int | None:
        """Year parsed from publicationDate."""
        if self.publicationDate:
            try:
                return int(self.publicationDate[:4])
            except ValueError:
                return None
        return None

    @computed_field
    @property
    def journal_name(self) -> str | None:
        """Container / journal name, or None when empty."""
        return self.container.name or None

    @computed_field
    @property
    def author_names(self) -> list[str]:
        """Non-empty full names of all authors."""
        return [a.fullName for a in self.authors if a.fullName]

    @computed_field
    @property
    def license(self) -> str | None:
        """First non-empty license string found across instances."""
        for inst in self.instances:
            if inst.license:
                return inst.license
        return None

    def __str__(self) -> str:
        parts = []
        if self.mainTitle:
            parts.append(self.mainTitle[:80])
        if self.publication_year:
            parts.append(f"({self.publication_year})")
        if self.doi:
            parts.append(f"DOI:{self.doi}")
        return " | ".join(parts) if parts else f"ResearchProduct(id={self.id!r})"

aireloom.Project

Bases: BaseEntity

Model representing an OpenAIRE Project entity.

Captures identifiers, title, funding, duration, and related metadata. Inherits the id field from BaseEntity.

Source code in packages/aireloom/src/aireloom/models/project.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
class Project(BaseEntity):
    """Model representing an OpenAIRE Project entity.

    Captures identifiers, title, funding, duration, and related metadata.
    Inherits the ``id`` field from ``BaseEntity``.
    """

    originalIds: SafeList[str] = Field(default_factory=list)
    code: str | None = None
    acronym: SafeStr = ""
    title: SafeStr = ""
    callIdentifier: str | None = None
    fundings: SafeList[Funding] = Field(default_factory=list)
    funding: SafeFundingHierarchy = Field(default_factory=FundingHierarchy)
    granted: SafeGrant = Field(default_factory=Grant)
    h2020Programmes: SafeList[H2020Programme] = Field(default_factory=list)
    keywords: SafeList[str] = Field(default_factory=list)
    openAccessMandateForDataset: bool | None = None
    openAccessMandateForPublications: bool | None = None
    # Dates are kept as strings: parts may be missing or null.
    startDate: str | None = None
    endDate: str | None = None
    subjects: SafeList[str] = Field(default_factory=list)
    summary: SafeStr = ""
    websiteUrl: str | None = None
    links: SafeList[ProjectLink] = Field(default_factory=list)

    @computed_field
    @property
    def funder_name(self) -> str | None:
        if self.fundings:
            f = self.fundings[0]
            return f.shortName or f.name or None
        return None

    @computed_field
    @property
    def funder_jurisdiction(self) -> str | None:
        if self.fundings:
            return self.fundings[0].jurisdiction
        return None

    @computed_field
    @property
    def start_year(self) -> int | None:
        if self.startDate:
            try:
                return int(self.startDate[:4])
            except ValueError:
                return None
        return None

    @computed_field
    @property
    def end_year(self) -> int | None:
        if self.endDate:
            try:
                return int(self.endDate[:4])
            except ValueError:
                return None
        return None

    def __str__(self) -> str:
        parts = []
        if self.title:
            parts.append(self.title[:80])
        if self.code:
            parts.append(f"[{self.code}]")
        if self.funder_name:
            parts.append(f"funded by {self.funder_name}")
        return " | ".join(parts) if parts else f"Project(id={self.id!r})"

    @field_validator("keywords", mode="before")
    @classmethod
    def parse_keywords_string(cls, v: Any) -> Any:
        """Split a delimited keyword string (comma or semicolon) into a list."""
        if isinstance(v, str):
            stripped = v.strip()
            if not stripped:
                return []
            for delimiter in (",", ";"):
                if delimiter in stripped:
                    return [
                        part.strip()
                        for part in stripped.split(delimiter)
                        if part.strip()
                    ]
            return [stripped]
        return v

aireloom.Organization

Bases: BaseEntity

Model representing an OpenAIRE Organization entity.

Captures names, website, country, persistent identifiers, funding records, provenance, and related entity links. Inherits the id field from BaseEntity.

Source code in packages/aireloom/src/aireloom/models/organization.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Organization(BaseEntity):
    """Model representing an OpenAIRE Organization entity.

    Captures names, website, country, persistent identifiers, funding records,
    provenance, and related entity links. Inherits the ``id`` field from
    ``BaseEntity``.
    """

    legalShortName: SafeStr = ""
    legalName: SafeStr = ""
    alternativeNames: SafeList[str] = Field(default_factory=list)
    websiteUrl: str | None = None
    country: SafeCountry = Field(default_factory=Country)
    pids: SafeList[Pid] = Field(default_factory=list)
    originalIds: SafeList[str] = Field(default_factory=list)
    collectedFrom: SafeList[SafeCfHbKeyValue] = Field(default_factory=list)
    fundings: SafeList[FundingHierarchy] = Field(default_factory=list)
    links: SafeList[RelatedRecord] = Field(default_factory=list)

    @computed_field
    @property
    def ror_id(self) -> str | None:
        return extract_pid_by_scheme(self.pids, "ror")

    @computed_field
    @property
    def country_code(self) -> str | None:
        return (
            self.country.code
            if self.country.code and self.country.code != "UNKNOWN"
            else None
        )

    def __str__(self) -> str:
        parts = []
        if self.legalName:
            parts.append(self.legalName)
        if self.country_code:
            parts.append(f"({self.country_code})")
        if self.ror_id:
            parts.append(f"ROR:{self.ror_id}")
        return " | ".join(parts) if parts else f"Organization(id={self.id!r})"

aireloom.DataSource

Bases: BaseEntity

Model representing an OpenAIRE Data Source entity.

A data source in OpenAIRE can be a repository, journal, aggregator, etc. Inherits the id field from BaseEntity.

Source code in packages/aireloom/src/aireloom/models/data_source.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class DataSource(BaseEntity):
    """Model representing an OpenAIRE Data Source entity.

    A data source in OpenAIRE can be a repository, journal, aggregator, etc.
    Inherits the ``id`` field from ``BaseEntity``.
    """

    originalIds: SafeList[str] = Field(default_factory=list)
    pids: SafeList[Pid] = Field(default_factory=list)
    type: SafePid = Field(default_factory=Pid)
    openaireCompatibility: str | None = None
    officialName: SafeStr = ""
    englishName: SafeStr = ""
    websiteUrl: str | None = None
    logoUrl: str | None = None
    dateOfValidation: str | None = None
    description: SafeStr = ""
    subjects: SafeList[str] = Field(default_factory=list)
    languages: SafeList[str] = Field(default_factory=list)
    contentTypes: SafeList[str] = Field(default_factory=list)
    releaseStartDate: str | None = None
    releaseEndDate: str | None = None
    accessRights: str | None = None
    uploadRights: str | None = None
    databaseAccessRestriction: str | None = None
    dataUploadRestriction: str | None = None
    versioning: bool | None = None
    citationGuidelineUrl: str | None = None
    pidSystems: str | None = None
    certificates: str | None = None
    policies: SafeList[str] = Field(default_factory=list)
    missionStatementUrl: str | None = None
    journal: SafeContainer = Field(default_factory=Container)
    # Harvesting endpoints (e.g. OAI-PMH base URL), added upstream in 1.5.0.
    endpoints: SafeList[str] = Field(default_factory=list)
    collectedFrom: SafeList[SafeCfHbKeyValue] = Field(default_factory=list)
    thematic: bool | None = None
    eoscdatasourcetype: SafeCodeLabel = Field(default_factory=CodeLabel)
    jurisdiction: SafeCodeLabel = Field(default_factory=CodeLabel)
    odlanguages: SafeList[str] = Field(default_factory=list)
    openaireCompatibilityId: str | None = None
    links: SafeList[RelatedRecord] = Field(default_factory=list)

    @computed_field
    @property
    def type_name(self) -> str | None:
        return self.type.value or None

    def __str__(self) -> str:
        name = self.officialName or self.englishName
        if name:
            return name
        return f"DataSource(id={self.id!r})"

aireloom.Person

Bases: BaseEntity

Model representing an OpenAIRE Person entity.

Captures names, identifiers (pid items are {value, typeCode, typeLabel}, e.g. ORCID), biography, topics, measures, context, and co-authors. Inherits the id field from BaseEntity.

Reference: https://graph.openaire.eu/docs/api/entities/person

Source code in packages/aireloom/src/aireloom/models/person.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class Person(BaseEntity):
    """Model representing an OpenAIRE Person entity.

    Captures names, identifiers (``pid`` items are ``{value, typeCode,
    typeLabel}``, e.g. ORCID), biography, topics, measures, context, and
    co-authors. Inherits the ``id`` field from ``BaseEntity``.

    Reference: https://graph.openaire.eu/docs/api/entities/person
    """

    originalId: SafeList[str] = Field(default_factory=list)
    pid: SafeList[TypedPid] = Field(default_factory=list)
    givenName: SafeStr = ""
    familyName: SafeStr = ""
    alternativeNames: SafeList[str] = Field(default_factory=list)
    biography: SafeStr = ""
    subject: SafeList[PersonTopic] = Field(default_factory=list)
    indicator: SafeList[Measure] = Field(default_factory=list)
    context: SafeList[Context] = Field(default_factory=list)
    consent: bool | None = None
    coAuthors: SafeList[str] = Field(default_factory=list)

    @computed_field
    @property
    def orcid(self) -> str | None:
        return extract_orcid(self.originalId, self.id, self.pid)

    @computed_field
    @property
    def full_name(self) -> str:
        parts = [n for n in (self.givenName, self.familyName) if n]
        return " ".join(parts)

    def __str__(self) -> str:
        name = self.full_name
        if name and self.orcid:
            return f"{name} (ORCID:{self.orcid})"
        if name:
            return name
        return f"Person(id={self.id!r})"

aireloom.Relation

Bases: BaseModel

A single relation link between two scholarly entities.

Source code in packages/aireloom/src/aireloom/models/relation.py
50
51
52
53
54
55
56
57
58
class Relation(BaseModel):
    """A single relation link between two scholarly entities."""

    source: Node | None = None
    target: Node | None = None
    relType: RelType | None = None
    provenance: SafeList[str] = Field(default_factory=list)

    model_config = ConfigDict(extra="allow")

aireloom.ScholixRelationship

Bases: BaseModel

A single Scholix relationship link between two scholarly entities.

Source code in packages/aireloom/src/aireloom/models/scholix.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
class ScholixRelationship(BaseModel):
    """A single Scholix relationship link between two scholarly entities."""

    link_provider: SafeList[ScholixLinkProvider] = Field(
        alias="LinkProvider", default_factory=list
    )
    relationship_type: ScholixRelationshipType | None = Field(
        alias="RelationshipType", default=None
    )
    source: ScholixEntity | None = Field(alias="Source", default=None)
    target: ScholixEntity | None = Field(alias="Target", default=None)
    link_publication_date: datetime | None = Field(
        alias="LinkPublicationDate",
        default=None,
        description="Date the link was published.",
    )
    license_url: str | None = Field(alias="LicenseURL", default=None)
    harvest_date: str | None = Field(alias="HarvestDate", default=None)

    model_config = ConfigDict(populate_by_name=True, extra="allow")