Skip to content

API reference

Generated from the source with mkdocstrings.

Client

aletheca.AlethecaClient

Bases: BaseApiClient

Client for the OpenAlex API.

Credentials resolve in the constructor: an explicit api_key argument wins, then :class:AlethecaSettings (ALETHECA_API_KEY or the consumer-legacy ALETHECA_OPENALEX_API_KEY env name). Without a key the client shares OpenAlex's $0.10/day per-IP budget and cannot use cursor paging past the first page; a free key fixes both. Usage examples live in the README and the documentation quick start.

works cached property

The works resource client.

authors cached property

The authors resource client.

sources cached property

The sources resource client.

institutions cached property

The institutions resource client.

topics cached property

The topics resource client.

keywords cached property

The keywords resource client.

publishers cached property

The publishers resource client.

funders cached property

The funders resource client.

awards cached property

The awards resource client.

locations cached property

The locations resource client (the per-copy index).

The links resource client (typed one-hop work edges).

last_rate_limit_headers property

Return x-ratelimit-* headers captured from the most recent response.

autocomplete(query, *, entity_type=None, filters=None) async

Free typeahead/ID resolution; returns up to 10 rows per call.

entity_type restricts to one autocomplete route ("works", "authors", "institutions", "sources", "topics", "keywords", "concepts", "publishers", or "funders"; OpenAlex does not provide /autocomplete/awards). Optional filters narrows candidates using OpenAlex filter syntax. Costs no credits.

rate_limit() async

Return the key's remaining daily budget and per-second caps.

Free, costs no credits; useful as a guard before large jobs.

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

Send a request with retries, mapping keyless 401s to clear errors.

OpenAlex 401s most often mean cursor paging without an API key; the re-raised message says how to fix it (OX-02).

on_response(response)

Capture OpenAlex x-ratelimit-* headers from the latest response.

is_retryable(response)

Veto retries for 429s whose reason is daily_budget.

A daily-budget 429 will not succeed before the UTC midnight reset, so retrying only burns the caller's remaining budget (OX-15).

Sync client

aletheca.AlethecaSyncClient

Bases: SyncBaseApiClient

Client for the OpenAlex API.

Credentials resolve in the constructor: an explicit api_key argument wins, then :class:AlethecaSettings (ALETHECA_API_KEY or the consumer-legacy ALETHECA_OPENALEX_API_KEY env name). Without a key the client shares OpenAlex's $0.10/day per-IP budget and cannot use cursor paging past the first page; a free key fixes both. Usage examples live in the README and the documentation quick start.

works cached property

The works resource client.

authors cached property

The authors resource client.

sources cached property

The sources resource client.

institutions cached property

The institutions resource client.

topics cached property

The topics resource client.

keywords cached property

The keywords resource client.

publishers cached property

The publishers resource client.

funders cached property

The funders resource client.

awards cached property

The awards resource client.

locations cached property

The locations resource client (the per-copy index).

The links resource client (typed one-hop work edges).

last_rate_limit_headers property

Return x-ratelimit-* headers captured from the most recent response.

autocomplete(query, *, entity_type=None, filters=None)

Free typeahead/ID resolution; returns up to 10 rows per call.

entity_type restricts to one autocomplete route ("works", "authors", "institutions", "sources", "topics", "keywords", "concepts", "publishers", or "funders"; OpenAlex does not provide /autocomplete/awards). Optional filters narrows candidates using OpenAlex filter syntax. Costs no credits.

rate_limit()

Return the key's remaining daily budget and per-second caps.

Free, costs no credits; useful as a guard before large jobs.

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

Send a request with retries, mapping keyless 401s to clear errors.

OpenAlex 401s most often mean cursor paging without an API key; the re-raised message says how to fix it (OX-02).

on_response(response)

Capture OpenAlex x-ratelimit-* headers from the latest response.

is_retryable(response)

Veto retries for 429s whose reason is daily_budget.

A daily-budget 429 will not succeed before the UTC midnight reset, so retrying only burns the caller's remaining budget (OX-15).

The sync twins of the resource clients are exported from the package root (WorksSyncClient, AuthorsSyncClient, and so on). They mirror the async resource clients method for method.

Settings

aletheca.AlethecaSettings

Bases: BaseApiSettings

OpenAlex-specific client settings.

Inherits timeout, max_retries, max_retry_wait, max_requests_per_second, max_concurrency, rate_limits, user_agent and mailto from :class:bibliofabric.config.BaseApiSettings and sets OpenAlex defaults (10 req/s, concurrency 5, semantic search 1 req/s).

The polite pool no longer exists: since February 2026 OpenAlex ignores mailto and meters unkeyed traffic at $0.10/day per IP. A free API key raises the budget to $1/day and is required for cursor paging beyond the first page. Get one at https://openalex.org/settings/api.

openalex_api_key (and env ALETHECA_OPENALEX_API_KEY) is accepted at runtime as a deprecated alias for api_key; typed callers should pass api_key= directly.

Resource clients

Each resource client inherits the generic operations from bibliofabric.ResourceClient (get, search, iterate, collect, first, count, batch_get) through aletheca._async.dialect.OpenAlexResourceClient. Only class-specific members are shown here.

aletheca._async.works.WorksClient

Bases: OpenAlexResourceClient[Work]

Client for the /works endpoint.

Adds the works-only query features: corpus/include_pulled/ include_parts, corpus-aware sample(), the scoped search.* parameters, and DOI-based batch retrieval.

search(filters=None, *, query=None, sort=None, select=None, page=None, page_size=None, cursor=None, on_error='raise', failures=None, params=None, corpus=None, include_parts=None, include_pulled=None, rerank=False) async

Search works; accepts the works-only corpus controls.

corpus selects which works answer: core (default upstream) excludes pulled and part works, expansion is the expansion set, all is everything. include_parts/include_pulled re-add those subsets to core. Note that a is_pulled/is_retracted filter re-includes pulled works on its own.

rerank=True reorders the top 100 of a relevance-sorted search (costs 10 extra credits and requires the relevance sort a query gives you); page.meta["reranked"] reports whether it applied.

search_scoped(text, *, scope='title_and_abstract', filters=None, params=None, **kwargs) async

Search works under one scoped search.* parameter.

Scopes: title, title_and_abstract, title_abstract_keywords, exact (supports wildcards and proximity operators), and semantic (embedding search; max 50 results, 1 request/second, and only its whitelisted filters combine). Only one search parameter is allowed per request; a search costs 10 credits.

sample(n, *, seed=None, filters=None, query=None, sort=None, select=None, page=None, page_size=None, cursor=None, on_error='raise', failures=None, params=None, corpus=None, include_parts=None, include_pulled=None, rerank=False) async

Return a random sample of up to n works (max 10,000).

Pass seed for reproducibility, and works-only corpus / include_parts / include_pulled / rerank controls. Page.total reports the sample size, not the size of the filtered corpus.

batch_get_by_doi(dois, *, batch_size=None) async

Fetch works by DOI, batched as pipe-joined OR filters.

DOIs are normalized (URL prefixes stripped, lowercased) and split into chunks of batch_size (default 100, the OpenAlex OR cap). Returns {normalized doi: Work}; DOIs not found are absent.

batch_get_by_openalex_id(ids, *, batch_size=None) async

Fetch works by OpenAlex id (bare W... or full URL).

citing(work_id, *, limit=100, filters=None, sort=None) async

Collect works that cite work_id, bounded by limit.

referenced(work_id, *, limit=100) async

Fetch (up to limit of) the works referenced by work_id.

oa_pdf_urls(doi_or_id) async

Return downloadable PDF URLs for a work, best OA copy first.

Reads pdf_url from best_oa_location, then primary_location, then the remaining locations; duplicates keep their first position. Returns [] when no location carries a PDF. OpenAlex's own paid PDF copies (content_urls.pdf) are not included.

aletheca._async.authors.AuthorsClient

Bases: OpenAlexResourceClient[Author]

Client for the /authors endpoint.

batch_get_by_openalex_id(ids, *, batch_size=None) async

Fetch authors by OpenAlex id (bare A... or full URL).

aletheca._async.locations.LocationsClient

Bases: OpenAlexResourceClient[LocationRecord]

Client for the /locations endpoint.

One row per copy of a work at one source (the per-copy index used for OA-copy hunting and repository-harvest audits). Rows are addressed by namespaced ids such as doi:10.7717/peerj.4375 or pmh:oai:arXiv.org:1706.03762; get/search/iterate behave like on the entity endpoints. A list request costs one credit.

normalize_id(value)

Keep namespaced ids intact: the single route 404s on bare DOIs.

Only URL and route prefixes are stripped; the doi:/pmh:/ pmid: namespace and the value's case stay as given.

aletheca._async.links.LinksClient

Bases: OpenAlexResourceClient[Link]

Client for the /links endpoint.

Typed one-hop edges between works, each labeled with a link type (https://openalex.org/link-types/citation and the part-of link types). origin() lists the edges leaving a work, target() the edges pointing at it; get/search/iterate are available for raw filter=origin:/target: queries.

origin(work_id, *, limit=100, link_type=None) async

Collect the edges leaving work_id (what it cites or contains).

Fetches filter=origin:<id> with cursor paging, up to limit edges. Ids normalize (bare W... or full URL). link_type keeps one kind of edge (citation, volume, component, data-series, part, or review); it accepts a short value or a full link-type URL.

target(work_id, *, limit=100, link_type=None) async

Collect the edges pointing at work_id (what cites or contains it).

Fetches filter=target:<id> with cursor paging, up to limit edges; heavily cited works need a small limit. link_type keeps one kind of edge, like origin().

Filter models

Every filter model dumps with by_alias=True into OpenAlex dot-notation keys and allows extra fields.

aletheca.filters.WorksFilters

Bases: BaseModel

Filter model for the works endpoint.

aletheca.filters.AuthorsFilters

Bases: BaseModel

Filter model for the authors endpoint.

aletheca.filters.SourcesFilters

Bases: BaseModel

Filter model for the sources endpoint.

aletheca.filters.InstitutionsFilters

Bases: BaseModel

Filter model for the institutions endpoint.

aletheca.filters.TopicsFilters

Bases: BaseModel

Filter model for the topics endpoint.

aletheca.filters.KeywordsFilters

Bases: BaseModel

Filter model for the keywords endpoint.

aletheca.filters.PublishersFilters

Bases: BaseModel

Filter model for the publishers endpoint.

aletheca.filters.FundersFilters

Bases: BaseModel

Filter model for the funders endpoint.

aletheca.filters.AwardsFilters

Bases: BaseModel

Filter model for the awards endpoint.

Aliases follow the live API's valid-filter list, which the API enumerates in the 400 error returned for invalid fields. funder.country_code, lead_investigator.id, co_lead_investigator.id, plain funder and display_name, and from_/to_*_date range filters are NOT valid on this endpoint and are absent here; extra="allow" still lets callers pass anything else.

aletheca.filters.LocationsFilters

Bases: BaseModel

Filter model for the /locations per-copy index endpoint.

aletheca.filters.LinksFilters

Bases: BaseModel

Filter model for the /links work-edge endpoint.

Dialect and helpers

aletheca.dialect

OpenAlex query dialect constants.

OPENALEX_DIALECT tells bibliofabric how OpenAlex names its query parameters. The resource-client base that consumes these constants lives in :mod:aletheca._async.dialect (its sync twin is generated from it).

OPENALEX_API_BASE_URL = 'https://api.openalex.org' module-attribute

MAX_OR_VALUES = 100 module-attribute

MAX_BASIC_PAGING_RESULTS = 10000 module-attribute

MAX_SAMPLE_SIZE = 10000 module-attribute

aletheca._async.dialect.OpenAlexResourceClient

Bases: ResourceClient[E]

Base for all OpenAlex resource clients.

build_batch_params(field, values)

Build one batch_get chunk as a pipe-joined OR filter.

DOI fields are normalized first (AT-03): URL forms would inject colons into the filter= value. The default field="id" maps to the openalex filter, because OpenAlex has no id filter.

build_filter_params(filters)

Serialize filters into OpenAlex's single filter parameter.

count(filters=None, *, query=None, params=None) async

Return the total number of matching entities at minimal cost.

Sends per_page=1 (the core default) plus select=id so the one-credit count request carries no entity payloads.

group_by(group_by, *, filters=None, query=None, cursor=None, params=None) async

Return one page of typed group_by buckets (costs one credit).

group_by accepts up to three comma-separated fields; deeper dimensions nest in :attr:GroupByBucket.groups. Responses return up to 200 buckets per call; pass cursor="*" (or use :meth:iterate_group_by) to advance across pages via page.next_cursor. page.total carries meta.count and page.meta preserves envelope metadata including groups_count.

item_path(id)

Return the single-entity path for id with external-ID prefixes.

OpenAlex bills bare DOI paths (/works/10.7717/...) at $0.0001 whereas prefixed singletons (/works/doi%3A10.7717%2F...) are free ($0). External IDs (DOI, ORCID, ROR, ISSN, PMID, PMCID) therefore get their namespace prefix before URL-encoding.

iterate_group_by(group_by, *, filters=None, query=None, limit=None, cursor=None, params=None)

Iterate over group_by buckets using cursor pagination.

normalize_id(value)

Canonicalize an identifier used in paths, batches, and dict keys.

Strips https://openalex.org/ and the entity path prefix, and normalizes DOIs, ORCIDs, RORs, ISSNs, PMIDs, and PMCIDs so caller inputs and returned record keys match across batch_get and filters.

record_keys(entity, field)

Return every normalized field value of entity.

Resolves OpenAlex's ids sub-object for external identifiers such as pmid/pmcid on works, orcid/observed_orcids on authors, ror on institutions, and issn/issn_l on sources, and maps field="openalex" to entity.id.

sample(n, *, seed=None, filters=None, query=None, sort=None, select=None, page=None, page_size=None, cursor=None, on_error='raise', failures=None, params=None) async

Return a random sample of up to n entities (max 10,000).

Pass seed for reproducibility. Page.total reports the sample size, not the size of the filtered corpus.

aletheca.reconstruct_abstract(inverted_index)

Reconstruct an abstract from OpenAlex's inverted index format.

Parameters:

Name Type Description Default
inverted_index dict[str, list[int]] | None

Mapping of word → list of positions.

required

Returns:

Type Description
str | None

The reconstructed abstract string, or None if input is None/empty.

Models

Entity models live in aletheca.models and re-export from the top-level package (from aletheca import Work, Author, ...). They are plain Pydantic models; see the source for the full field list.

aletheca.models.Work

Bases: BaseEntity

An OpenAlex Work entity.

reconstructed_abstract property

Reconstruct the full abstract text from the inverted index.

aletheca.models.GroupByBucket

Bases: BaseModel

One bucket of a group_by response.

Multi-field group_by (up to three comma-separated fields) nests the second and third dimension in groups.

aletheca.models.AutocompleteResult

Bases: BaseModel

One row of a free /autocomplete (or /autocomplete/{entity}) response.

aletheca.models.RateLimitStatus

Bases: BaseModel

The body of GET /rate-limit (free, costs no credits).

The echoed api_key field is ignored on purpose so the secret never lands in the model or its repr.

aletheca.models.LocationRecord

Bases: BaseModel

One row of the /locations per-copy index.

Each row is one copy of a work at one source, keyed by namespaced ids (doi:..., pmh:..., pmid:..., mag:...). source_id, source_name, and publisher are flattened from the row's source.

Bases: BaseModel

One typed edge of the /links citation-graph endpoint.

link_type is an OpenAlex link-type URL (for example https://openalex.org/link-types/citation) labeling how origin relates to target. OpenAlex renamed this field from relationship (removed from responses on 2026-12-07); validation accepts either name, and old /relationships/ urls are mapped to /link-types/ so snapshots from before the rename parse to the canonical form.