Metadata-Version: 2.4
Name: bibliofabric
Version: 0.9.0
Summary: Typed async and sync clients for scholarly infrastructure APIs: OpenAlex, OpenAIRE, Crossref, ROR, Zenodo, DataCite, and more, on one shared core
Author: Samuel Mok
Author-email: Samuel Mok <s.mok@utwente.nl>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.9.0
Requires-Dist: pydantic-settings>=2.9.1
Requires-Dist: tenacity>=9.0.0
Requires-Python: >=3.12
Project-URL: Homepage, https://github.com/utsmok/bibliofabric
Project-URL: Repository, https://github.com/utsmok/bibliofabric
Project-URL: Documentation, https://utsmok.github.io/bibliofabric/
Project-URL: Issues, https://github.com/utsmok/bibliofabric/issues
Project-URL: Changelog, https://github.com/utsmok/bibliofabric/blob/main/packages/bibliofabric/CHANGELOG.md
Description-Content-Type: text/markdown

# bibliofabric: Python clients for scholarly metadata APIs

*Samuel Mok // s.mok@utwente.nl*

`bibliofabric` is one package with typed asynchronous and synchronous clients
for scholarly APIs, on one shared core. The core owns what every such client
needs: HTTP with retries and throttling, authentication, error mapping, paging,
batch retrieval, identifier normalization, and typed resource clients. Each
client is a subpackage named after its source and adds only what is specific
to its API.

| Subpackage | API |
|---|---|
| `bibliofabric` | the core framework (no API of its own) |
| `bibliofabric.openalex` | OpenAlex |
| `bibliofabric.openaire` | OpenAIRE Graph API (V4), Scholexplorer |
| `bibliofabric.crossref` | Crossref REST API and the beta Data Citation API |
| `bibliofabric.ror` | ROR (research organizations and funders) |
| `bibliofabric.zenodo` | Zenodo REST API and OAI-PMH |
| `bibliofabric.datacite` | DataCite REST API and public GraphQL |
| `bibliofabric.opencitations` | OpenCitations Index and Meta APIs |
| `bibliofabric.doi` | DOI registration agency lookup, content negotiation, and Handle records |
| `bibliofabric.semanticscholar` | Semantic Scholar Graph, Recommendations, and Datasets APIs |
| `bibliofabric.orcid` | ORCID Public API v3.0 |
| `bibliofabric.europepmc` | Europe PMC REST web services and annotations API |
| `bibliofabric.wikidata` | Wikidata (action API, REST API, and SPARQL) |
| `bibliofabric.doaj` | DOAJ (open access journals and articles) |
| `bibliofabric.issn` | ISSN Portal |
| `bibliofabric.arxiv` | arXiv API |
| `bibliofabric.rxiv` | bioRxiv and medRxiv API |

## Installation

```bash
uv add bibliofabric
```

Requires Python 3.12 or newer. The clients `aireloom`, `aletheca`, and
`stavrophora` were folded into this package as `bibliofabric.openaire`,
`bibliofabric.openalex`, and `bibliofabric.crossref`; the
[migration guide](https://utsmok.github.io/bibliofabric/migration/) lists
every rename.

## Using a client

Every client ships an async client (`<Source>Client`) and a generated sync
twin (`<Source>SyncClient`) with the same API:

```python
from bibliofabric.openalex import OpenAlexClient, OpenAlexSyncClient, WorksFilters

filters = WorksFilters(publication_year=2024, is_oa=True)

async with OpenAlexClient() as client:
    page = await client.works.search(filters, query="photosynthesis")

with OpenAlexSyncClient() as client:
    page = client.works.search(filters, query="photosynthesis")
```

The sync client uses `httpx.Client`, `time.sleep`, and threads; it never
starts an event loop, so it works in plain scripts, in Jupyter, and inside a
running event loop. Each client documents its endpoints, filters, credentials,
and the quirks of its upstream API at
[utsmok.github.io/bibliofabric](https://utsmok.github.io/bibliofabric/).

## Building a client

A client defines four things: a settings subclass, a response unwrapper, a
query dialect, and one `ResourceClient` subclass per endpoint.

```python
from bibliofabric import (
    BaseApiClient,
    BaseApiSettings,
    QueryDialect,
    ResourceClient,
    ResponseUnwrapper,
)
from pydantic import BaseModel
from pydantic_settings import SettingsConfigDict


class FooSettings(BaseApiSettings):
    model_config = SettingsConfigDict(
        env_prefix="FOO_", env_file=".env", extra="ignore"
    )


class Work(BaseModel):
    id: str = ""
    title: str = ""
    doi: str | None = None


class FooUnwrapper:
    """Unwraps the Foo API envelope: {"results": [...], "total": n}."""

    def results(self, body):
        return body.get("results", [])

    def item(self, body):
        return body

    def total(self, body):
        return body.get("total")

    def next_cursor(self, body):
        return body.get("next_cursor")

    def meta(self, body):
        return {k: v for k, v in body.items() if k != "results"}


DIALECT = QueryDialect(
    page_size_param="per_page",
    max_page_size=200,
    query_param="search",
    select_param="select",
)


class Works(ResourceClient[Work]):
    path = "works"
    model = Work
    dialect = DIALECT


class FooClient(BaseApiClient):
    def __init__(self, settings=None, auth=None):
        super().__init__(
            base_url="https://api.foo.org/v1",
            settings=settings or FooSettings(),
            unwrapper=FooUnwrapper(),
            auth=auth,
        )
        self.works = Works(self)
```

Using the client:

```python
async with FooClient() as client:
    work = await client.works.get("W123")  # 404 raises NotFoundError
    page = await client.works.search(query="algae")  # returns Page[Work]
    async for work in client.works.iterate(page_size=100, limit=500):
        ...
    count = await client.works.count()
    batch = await client.works.batch_get(["W1", "W2", "W3"])
```

`get()`, `search()`, and `count()` return typed results; iteration supports
cursor, page, and offset paging depending on the dialect. Errors, retries, and
limits are described in the [errors page](https://utsmok.github.io/bibliofabric/bibliofabric/errors/).

Every client built on the framework also gets a generated sync twin. Sync
classes follow the `FooClient` -> `FooSyncClient` naming rule:

```python
with FooSyncClient() as client:
    work = client.works.get("W123")
    page = client.works.search(query="algae")
    for work in client.works.iterate(page_size=100, limit=500):
        ...
```

The [building a client guide](https://utsmok.github.io/bibliofabric/bibliofabric/writing-a-client/)
walks through adding a client to this package.

## Contributing and license

See the [contributing guide](https://utsmok.github.io/bibliofabric/contributing/).
This project is licensed under the MIT License.
