Page through results
Every resource exposes the same paging tools: search() returns one typed
Page, iterate() walks every match, and collect(), first(), and
count() build on iterate(). The examples here use
OpenAlex, which pages with cursors. The examples on
this page run in an async context; if you work in a notebook or a script,
see Async and sync clients.
Get one page of results
search() returns a Page with results, total, next_cursor, page,
and meta:
| Field | Holds |
|---|---|
results |
The validated models on this page |
total |
Number of matches, or None when the API does not report it |
next_cursor |
Cursor for the next page, or None |
page |
Page number for page-numbered APIs, or None |
meta |
The raw response envelope minus the results, such as facets |
from bibliofabric.openalex import OpenAlexClient
client = OpenAlexClient()
Later blocks reuse this client.
page = await client.works.search(query="crispr", page_size=5, cursor="*")
print("total:", page.total)
print("ids:", [w.id.rsplit("/", 1)[1] for w in page.results])
print("next_cursor:", page.next_cursor)
total: 420426
ids: ['W2239190724', 'W2062280978', 'W1876354170', 'W4213164504', 'W2153355254']
next_cursor: IlsxMzAuMDA4MzksIDExMzE2NjcyMDAwMDAsICdodHRwczovL29wZW5hbGV4Lm9yZy9XMjE1MzM1NTI1NCddIg==
On OpenAlex, next_cursor is set only when the request asks for cursor
paging with cursor="*"; the client page explains its basic-paging limit.
Cursor-paged APIs take different start tokens, and page-numbered APIs take
page= instead, so check the client page for the first call.
A Page also iterates over its records, and len(page) counts them, so
for work in page: is the same as for work in page.results:.
Walk every match
iterate() walks all matches and yields one model at a time, whatever
paging style the API uses. Pass limit= to stop early:
count = 0
async for work in client.works.iterate(query="crispr", limit=7):
count += 1
print("iterated:", count)
iterated: 7
iterate() chooses the page size itself (100 for OpenAlex) and follows
cursors, page numbers, or offsets as the API requires. For APIs with no
paging at all it fetches everything once and yields the records.
Collect, count, or take the first
Three helpers cover the common shapes of that walk:
first = await client.works.first(query="crispr")
print("first:", first.id.rsplit("/", 1)[1])
total = await client.works.count(query="crispr")
print("count:", total)
collected = await client.works.collect(query="crispr", limit=3, select=["id", "doi"])
print("collected:", len(collected))
first: W2239190724
count: 420426
collected: 3
first() returns None when nothing matches, and count() requests a
minimal page because only the total is needed. When the API reports no
total, count() raises ConfigurationError.
Resume a cursor harvest
A cursor harvest can stop and continue later. Capture cursors with the
on_page callback, save the last one, and pass it back as cursor=:
page = await client.works.search(query="crispr", page_size=5, cursor="*")
saved = page.next_cursor
resume = await client.works.search(query="crispr", page_size=5, cursor=saved)
print("resumed ids:", [w.id.rsplit("/", 1)[1] for w in resume.results])
resumed ids: ['W2791311992', 'W1965175092', 'W2186989880', 'W3178418858', 'W2047032063']
The callback receives the page number and the cursor to resume from:
def on_page(number: int, cursor: str | None) -> None:
print(f"page {number} checkpoint, next cursor: {cursor}")
count = 0
async for work in client.works.iterate(
query="crispr", page_size=5, limit=8, on_page=on_page
):
count += 1
print("iterated:", count)
page 1 checkpoint, next cursor: IlsxMzAuMDA4MzksIDExMzE2NjcyMDAwMDAsICdodHRwczovL29wZW5hbGV4Lm9yZy9XMjE1MzM1NTI1NCddIg==
page 2 checkpoint, next cursor: IlsxMjYuMTc4NjgsIDEyNjI4MjI0MDAwMDAsICdodHRwczovL29wZW5hbGV4Lm9yZy9XMjA0NzAzMjA2MyddIg==
iterated: 8
Passing a saved cursor back into iterate(cursor=...) continues the walk
from that point. Cursor resuming works only on cursor-paged APIs; on a
page-numbered API a later run restarts from page=1.
Page-numbered APIs
APIs without cursors, such as Zenodo, take page=:
import asyncio
from bibliofabric.zenodo import ZenodoClient
async def main() -> None:
async with ZenodoClient() as client:
page = await client.records.search(query="open science", page=1, page_size=3)
print("total:", page.total, "page:", page.page)
print("ids:", [r.id for r in page.results])
second = await client.records.search(query="open science", page=2, page_size=3)
print("page 2 ids:", [r.id for r in second.results])
asyncio.run(main())
total: 885919 page: 1
ids: [10057114, 10057066, 10141912]
page 2 ids: [15083098, 17579089, 11494961]
next_cursor stays None on these APIs, and iterate() still works: it
increments the page number until a page comes back empty. Page-numbered and
offset-paged APIs cap how deep you can reach, for example Zenodo past result
10000; the client page states the cap.
APIs without paging
OpenCitations has no paging: each call returns
the complete result, and page and next_cursor stay None:
import asyncio
from bibliofabric.opencitations import OpenCitationsClient
async def main() -> None:
async with OpenCitationsClient() as client:
citations = await client.index.citations("doi:10.1109/5.771073")
print("rows:", len(citations))
for row in citations[:2]:
print(row.citing.split()[0], "->", row.cited.split()[0])
asyncio.run(main())
rows: 98
omid:br/06010098945 -> omid:br/06190695940
omid:br/06010315733 -> omid:br/06190695940
Fetch many ids at once
batch_get(ids) fetches many entities in one call. It normalizes and
deduplicates the ids, fetches them in concurrent chunks, and returns a dict
keyed by the normalized id. An id with no match is simply absent from the
result.
found = await client.works.batch_get(
[
"10.1038/nature12373",
"https://doi.org/10.1109/5.771073",
"10.1038/nature12373",
],
field="doi",
select=["id", "title", "doi"],
)
print(len(found), "result(s)")
for doi, work in found.items():
print(doi, "->", work.title)
2 result(s)
10.1038/nature12373 -> Nanometre-scale thermometry in a living cell
10.1109/5.771073 -> Toward unique identifiers
The two URL forms and the repeated DOI collapse to two results, and a batch
that also asked for "10.9999/not-real" returned the same two keys, so a
missing id is absent rather than None. field=
names the identifier to match ("doi", "id", "orcid", and similar),
batch_size= sets the chunk size, concurrency= bounds the parallel
chunks, and on_error="skip" with failures= collects rows that fail
validation instead of raising. Some clients add ready-made batch helpers, for
example client.works.batch_get_by_doi() on
OpenAlex; the batch routes of the other clients are
described on their usage pages, for example
Semantic Scholar.