Metadata-Version: 2.5
Name: americanbible-api-bible-sdk
Version: 1.5.0
Summary: Python SDK for the api.bible REST API
Project-URL: Homepage, https://api.bible/
Project-URL: Repository, https://github.com/americanbible/api-bible-sdks
Project-URL: Issues, https://github.com/americanbible/api-bible-sdks/issues
Author: American Bible Society
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: api.bible,bible,scripture,sdk
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: anyio<5,>=4
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2
Description-Content-Type: text/markdown

# api-bible-sdk (Python)

A production-quality Python SDK for [api.bible](https://api.bible/).

- Synchronous client with attribute-style resources (`client.bibles.list(...)`)
- API-key authentication
- Automatic retries with full-jitter exponential backoff (honors `Retry-After`), bounded by a total-time budget
- Typed [Pydantic v2](https://docs.pydantic.dev/) models — full type hints, validated responses
- A granular exception hierarchy
- Requires **Python 3.11+** (see [Supported Python versions](#supported-python-versions))

> Runtime dependencies: `httpx` and `pydantic>=2`. Installing this SDK pins your
> environment to Pydantic v2.

## Install

```bash
pip install americanbible-api-bible-sdk
```

### Supported Python versions

The SDK supports every CPython version that has not reached
[end of life](https://devguide.python.org/versions/), and CI tests each one.
Currently that's **3.11 through 3.14**.

- A new CPython version is added once the SDK's dependencies ship wheels for it.
- A version that reaches end of life is dropped in the **next minor release**,
  never in a patch release. `requires-python` is raised at the same time, so pip
  and uv on the old interpreter keep resolving the last compatible release.

**Python 3.10** reached end of life in October 2026 and is not supported. 1.5.0,
the first release on PyPI, requires Python 3.11+.

## Quickstart

```python
from api_bible import BibleClient

with BibleClient.from_env() as client:  # reads API_BIBLE_KEY (or BIBLE_API_KEY)
    bibles = client.bibles.list(language="eng")
    for bible in bibles:
        print(bible.id, bible.name)

    bible = client.bibles.get(bibles[0].id)
    print(bible.abbreviation)
```

Or pass the key explicitly:

```python
client = BibleClient(api_key="your-key-here")
```

### Async

`AsyncBibleClient` takes the same arguments and has the same resources, methods,
models and errors as `BibleClient`. You await each call, and you close the client
with `async with` or `await client.aclose()`. It runs on asyncio and on trio.

```python
import asyncio

from api_bible import AsyncBibleClient


async def main() -> None:
    async with AsyncBibleClient.from_env() as client:
        bibles = await client.bibles.list(language="eng")
        chapter = await client.chapters.get(bibles[0].id, "GEN.1")
        print(chapter.reference)


asyncio.run(main())
```

Retries, timeouts, the `Retry-After` and `max_elapsed` limits, redirects, the
response size cap and api-key handling all behave exactly as described below for
`BibleClient`. The difference is that backoff waits with `anyio.sleep` instead of
blocking the thread. Pass your own pool as `http_client=httpx.AsyncClient(...)`.
`on_request` / `on_retry` observers are plain functions called inline on the event
loop, so keep them fast and non-blocking. `client.last_meta` is per task: a call
made in another task, including a child task of a task group, doesn't change it.
To tie metadata to a specific response, use a `*_with_meta` method.

## Error handling

```python
from api_bible import ApiError, AuthError, BibleClient, NotFoundError

with BibleClient.from_env() as client:
    try:
        client.verses.get("bba9f40183526463-01", "GEN.99.99")
    except NotFoundError:
        print("no such verse")  # unknown book, chapter, verse or passage id
    except AuthError as exc:
        # 401/403: a bad key, a used-up quota, or a bible id that is unknown or
        # not licensed to your key. They share a status code, so read the message.
        print(exc)
    except ApiError as exc:  # catches every HTTP failure
        print(exc.status_code, exc)
```

Hierarchy: `BibleError` → `ApiError` → {`AuthError`, `BadRequestError`,
`NotFoundError`, `ConflictError`, `UnprocessableEntityError`, `RateLimitError`,
`ServerError`, `NetworkError`}, plus `InvalidInputError` (bad caller input, or a
call on a closed client) and
`ValidationError` (response did not match the schema). `RateLimitError` (429) and `ServerError` (5xx) are retried
automatically. A `2xx` response that is empty or carries a non-JSON
`Content-Type` (e.g. a proxy's HTML error page) is treated as a failure and
raised as `ApiError` — it is not retried.

> **Note:** the `sections` endpoints (`sections.list_for_book` /
> `sections.list_for_chapter`) return `404` — surfaced as `NotFoundError` — for a
> book or chapter that has no section data, rather than an empty list. Wrap them in
> `try/except NotFoundError` when a book may lack sections.

**Redirects are not followed.** Every request is sent with
`follow_redirects=False`, including when you supply your own `httpx.Client`, and a
3xx response raises `ApiError` naming the redirect target's origin rather than
being followed. The `api-key` header would travel with a redirect, handing your
key to whatever host the `Location` names, and api.bible does not redirect in
normal operation — so a 3xx is worth looking at before the key goes out again.

When a `RateLimitError` propagates, the server's requested wait (if it sent one)
is available on the error so you can back off out-of-process:

```python
from api_bible import RateLimitError

try:
    client.bibles.list()
except RateLimitError as exc:
    print(exc.retry_after)  # seconds the server asked us to wait, or None
```

Every `ApiError` raised from a response also carries that response's `headers`
(lower-cased names), e.g. to quote a request-id header when contacting support.
It is `None` for a `NetworkError`, where no response arrived. Headers that can
carry a session or a credential (`Set-Cookie`, `Location`, `Content-Location`,
and any value containing your api-key) are left out, because exceptions tend to
end up in logs and error trackers.

## Configuration

```python
from api_bible import BibleClient, RetryConfig

client = BibleClient(
    api_key="...",
    timeout=10.0,  # per-attempt seconds
    retry=RetryConfig(
        max_attempts=5,
        base_delay=0.5,
        max_delay=30.0,  # ceiling on client-computed backoff
        max_retry_after=60.0,  # longest server Retry-After we'll honor
        max_elapsed=60.0,  # total-time budget across retries (None disables)
    ),
)
```

## Response metadata (FUMS)

Every response carries optional FUMS analytics metadata (api.bible's usage
tracking). On current responses the populated field is `meta.fums_token` (the
token you submit to report fair use); the older JS-embed fields (`fums`,
`fums_js`, `fums_js_include`) are often absent. There are two ways to read it:

- `client.last_meta` — the `Meta` from the calling thread's most recent call (or
  `None` if it failed or carried none). Convenient for the single-call case, but
  it's overwritten by the next call on the thread.
- The `*_with_meta` methods on the content endpoints (`chapters`, `verses`,
  `passages`, `sections`) return a `Result[T]` pairing `data` with the `meta` from
  *that* response. Prefer these when correlation matters or across threads.

```python
with BibleClient.from_env() as client:
    # Convenience: metadata from the most recent call on this thread.
    chapter = client.chapters.get(bible_id, chapter_id)
    print(client.last_meta)

    # Reliable: metadata tied to this exact response.
    result = client.chapters.get_with_meta(bible_id, chapter_id)
    print(result.data.reference, result.meta)
```

## Using this SDK under load

The client is synchronous, and retries sleep on the calling thread
(`time.sleep`). A few things to know when running it under concurrency or inside
a request handler:

- **Total retry time is bounded.** `RetryConfig.max_elapsed` defaults to 60s, so a
  single call won't park a worker for minutes during a rate-limit storm. If a
  server `Retry-After` exceeds the budget, the call gives up and the wait is left
  on `RateLimitError.retry_after` so you can back off out-of-process (e.g. requeue)
  instead of blocking the thread.
- **Pool timeouts fail fast.** A connection-pool timeout is *not* retried (that
  would only deepen the starvation). For high concurrency, size the pool with
  `limits`, and use an `httpx.Timeout` for per-phase (connect/read/write/pool)
  control:

  ```python
  import httpx
  from api_bible import BibleClient

  client = BibleClient(
      api_key="...",
      timeout=httpx.Timeout(10.0, connect=5.0),
      limits=httpx.Limits(max_connections=200, max_keepalive_connections=50),
  )
  ```

  Passing your own `http_client=httpx.Client(...)` still works and takes full
  control of the pool; in that case the client owns `timeout`/`limits` and the
  ones above are ignored. An `auth=` configured on that client still runs; the
  SDK sets the `api-key` after it, so the configured key always wins.

- **Share one client.** `BibleClient` and its underlying `httpx.Client` are safe to
  share across threads — reuse a single instance so connection pooling kicks in.
- **Response bodies are size-capped.** Each response is streamed and read under a
  limit (`max_response_bytes`, default 10 MiB); a body that exceeds it is aborted
  mid-stream with an `ApiError` rather than being buffered into memory (the attempt
  still reaches `on_request`, with `error="response too large"`). Raise the
  limit for unusually large payloads, or pass `max_response_bytes=None` to disable
  the cap entirely:

  ```python
  client = BibleClient(api_key="...", max_response_bytes=50 * 1024 * 1024)
  ```

- **Async code:** use `AsyncBibleClient` (see [Async](#async)). Its retries wait
  with `anyio.sleep`, so a rate-limit storm never blocks the event loop, and
  `max_elapsed` bounds each call in the same way. Observers run on the loop, so
  they must not block.

## Observability

The SDK logs to the `api_bible` logger (silent by default via a `NullHandler` —
configure a handler to see retry/give-up warnings and per-attempt debug lines).
It never logs the api-key, the query string or response bodies.

Every record also carries structured fields that JSON log handlers (e.g.
`python-json-logger`, structlog's stdlib bridge) emit as top-level keys:

| Field | On | Value |
|---|---|---|
| `api_bible_method`, `api_bible_path`, `api_bible_route` | all | HTTP method, concrete path, path template |
| `api_bible_call_id` | all | same for every record of one call (see `call_id` below) |
| `api_bible_attempt`, `api_bible_max_attempts` | all | 1-based attempt the record is about |
| `api_bible_status_code`, `api_bible_elapsed_ms` | per-response debug | |
| `api_bible_status_code`, `api_bible_reason` | retry / give-up warnings | status is `None` for a timeout or network error |
| `api_bible_delay_ms` | retry warning | scheduled backoff |
| `api_bible_retry_after_ms` | `Retry-After` give-up | server-requested wait |

The `api_bible_` prefix keeps them from colliding with fields your own log
filters add.

For metrics, pass an `on_request` observer. It's called once per HTTP attempt
(so a retried call fires several times) with a `RequestEvent` you can feed into
Prometheus/OpenTelemetry/StatsD — derive P99 from `elapsed_ms`, count outcomes
by `status_code`, track retries via `attempt`, and read the response `headers`
(e.g. rate-limit headers) to throttle proactively.

Tag metrics by `event.route`, the endpoint's path template
(`/bibles/{bible_id}/chapters/{chapter_id}`), not by `event.path`. `path` holds
the concrete ids, so using it as a Prometheus or OpenTelemetry label creates a
new time series for every bible, chapter and verse. Keep `path` for logs and
debugging.

```python
from api_bible import BibleClient, RequestEvent


def on_request(event: RequestEvent) -> None:
    # status_code is None when the attempt never got a response (timeout/transport);
    # event.error then holds a short reason ("timeout", "network error", "pool timeout").
    metrics.histogram("api_bible.latency_ms", event.elapsed_ms, tags={"route": event.route})
    metrics.increment(
        "api_bible.requests", tags={"route": event.route, "status": event.status_code}
    )
    # headers is None when no response arrived; keys are lower-cased.
    if event.headers and (remaining := event.headers.get("x-ratelimit-remaining")):
        metrics.gauge("api_bible.rate_limit_remaining", int(remaining))


client = BibleClient.from_env(on_request=on_request)
```

`on_request` fires per *attempt* but doesn't tell you when the SDK decides to
wait and retry. For that, pass an `on_retry` observer: it's called once per retry,
just before the backoff sleep, with a `RetryEvent` carrying the scheduled
`delay_ms`, the `reason` (`"HTTP 503"`, `"request timed out"`, `"network error"`),
and the server's `retry_after_ms` hint when present. Use it to count retries and
build a backoff histogram:

```python
from api_bible import BibleClient, RetryEvent


def on_retry(event: RetryEvent) -> None:
    metrics.increment("api_bible.retries", tags={"route": event.route, "reason": event.reason})
    metrics.histogram("api_bible.retry_delay_ms", event.delay_ms)


client = BibleClient.from_env(on_retry=on_retry)
```

A give-up (attempts exhausted, `max_elapsed` spent, or `Retry-After` past the
ceiling) emits no retry event — it surfaces as the raised exception and the final
`RequestEvent`.

Every event from one call, across all its attempts and retries, carries the
same `call_id`. Group by it to measure what your caller actually waited:
summing the call's `RequestEvent.elapsed_ms` and `RetryEvent.delay_ms` gives the
end-to-end latency including backoff. `elapsed_ms` alone is per-attempt latency,
which understates the true P99 when retries happen. Like `path`, `call_id` is
unique per call, so put it in logs or traces, not in metric labels.

Both observers must be thread-safe if you share the client across threads. With
`AsyncBibleClient` they are called inline on the event loop, so they must not
block either. Any exception either raises is caught and logged — it can never
break a request.

## Per-request headers

Every resource method accepts an optional `headers` mapping, applied to that one
request. Use it to propagate a distributed-tracing context or a correlation id
without building a separate client:

```python
client.chapters.get(
    "bba9f40183526463-01",
    "GEN.1",
    headers={"traceparent": ctx.traceparent},
)
```

Per-request headers override client-level `headers` of the same name, but can
never override the `api-key`. The SDK applies it last, at send time, through an
`httpx.Auth`, after client-level, per-request and your `http_client`'s own headers.
It sends the key only to the API's own origin (scheme, host and port), so a
request your `http_client`'s `auth=` makes elsewhere, such as a token refresh,
never carries it.

Header names and values must be ASCII strings. Anything else raises
`InvalidInputError`: from the constructor for client-level `headers`, or before
the request is sent for per-request ones.

## Development

The dev environment is managed with [uv](https://docs.astral.sh/uv/)
([install it](https://docs.astral.sh/uv/getting-started/installation/) once,
e.g. `brew install uv`). From `packages/python`:

```bash
# Create .venv with the SDK (editable) and the locked dev toolchain — what CI uses.
uv sync
source .venv/bin/activate
ruff check . && ruff format --check . && mypy && pytest --cov=api_bible
```

Runtime dependency ranges live in `pyproject.toml`. `uv.lock` pins the whole
dev, CI and release environment: the `dev` dependency group (pytest, ruff,
mypy) and the `release` group (build, twine, pip-audit). After editing
dependencies in `pyproject.toml`, run `uv lock` and commit `uv.lock` with the
change. To upgrade locked versions, run `uv lock --upgrade-package <name>`, or
`uv lock --upgrade` for everything. CI runs `uv sync --locked`, which fails if
`uv.lock` is out of date with `pyproject.toml`.

Dependabot opens a weekly grouped PR that updates `uv.lock` (ruff gets its own
PR, since it can change formatting), and CI fails the build on any known
vulnerability via `pip-audit`.

### Contract tests

Two tiers share one case table ([tests/contract/cases.py](https://github.com/americanbible/api-bible-sdks/blob/main/packages/python/tests/contract/cases.py)):

- **Offline** ([test_contract_fixtures.py](https://github.com/americanbible/api-bible-sdks/blob/main/packages/python/tests/contract/test_contract_fixtures.py)) replays
  recorded responses through the real client so the Pydantic models validate them exactly as in
  production. Runs in PR CI as part of `pytest`.
- **Live** ([test_contract_live.py](https://github.com/americanbible/api-bible-sdks/blob/main/packages/python/tests/contract/test_contract_live.py)) hits api.bible to catch
  schema drift. Self-skips without a key; runs nightly. Run it with
  `API_BIBLE_KEY=... pytest -m live tests/contract/test_contract_live.py`.

Regenerate the fixtures from the live API with
`API_BIBLE_KEY=... python tests/contract/record_fixtures.py`.

## Releasing

This package is published to PyPI independently of the JavaScript packages in
this monorepo, via [PyPI Trusted Publishing](https://docs.pypi.org/trusted-publishers/)
(OIDC — no stored token). See [CHANGELOG.md](https://github.com/americanbible/api-bible-sdks/blob/main/packages/python/CHANGELOG.md) for release history.

To cut a release:

1. Bump `__version__` in [src/api_bible/\_version.py](https://github.com/americanbible/api-bible-sdks/blob/main/packages/python/src/api_bible/_version.py)
   (SemVer) and move the `[Unreleased]` notes in `CHANGELOG.md` under the new
   version.
2. Merge to `main`, then push a matching tag: `git tag py-v1.2.3 && git push
   origin py-v1.2.3`.
3. The `Python Release` workflow verifies the tag is on `main` and matches
   `__version__`, runs the full lint/type/test gate, builds, checks the
   distribution with `twine check`, smoke-tests the wheel in a clean venv, and
   publishes to PyPI. Any failed check stops the release before upload.

To rehearse a release without publishing, run the workflow by hand (Actions →
Python Release → Run workflow): it runs every check and build step, and skips
the publish job.

**Rollback.** PyPI releases are immutable and cannot be deleted or overwritten.
To roll back a bad release: **yank** it on PyPI (existing pins keep working, but
new installs skip it), then fix forward by publishing a patched `X.Y.Z+1`. Never
attempt to re-publish the same version.

For incidents (yanking, failed contract checks, security advisories, and
compromised publishing credentials), see [RUNBOOK.md](https://github.com/americanbible/api-bible-sdks/blob/main/packages/python/RUNBOOK.md).

---

## License and terms

Licensed under the Apache License 2.0 — Copyright 2026 American Bible Society.
See [LICENSE](https://github.com/americanbible/api-bible-sdks/blob/main/packages/python/LICENSE). That covers this SDK's source code, and nothing else.

Your use of the API is governed by api.bible's
[Terms & Conditions](https://api.bible/terms-and-conditions), and the scripture
text and audio it returns are licensed by their publishers and rights holders —
not by this package. Most translations carry attribution, usage, and reporting
obligations of their own. Read the terms before you ship.
