Skip to content

Errors, retries, and rate limits

Every client raises the same exception hierarchy. A failed call raises a typed exception with the HTTP context attached, retries happen by default for transient failures, and the client paces itself so you stay under each API's limits. This page shows what you catch, what the library retries on its own, and what you tune when an API has its own budget.

What a failed call raises

A 404 raises NotFoundError, a 429 raises RateLimitError with the parsed Retry-After in .retry_after, 401 and 403 raise AuthError, and any other status of 400 or more raises APIError. Catching BibliofabricError catches every error the library raises. The full hierarchy and its attributes are in Errors.

A network failure raises NetworkError, and a request that exceeded the timeout raises TimeoutError. Passing unsupported search parameters raises ConfigurationError before any request is sent.

Every exception carries the HTTP context: .status_code, .request, and .response when a response exists. AuthError and APIError carry the parsed JSON error body in .body, and their message includes a short, sanitized summary of that body.

The example fetches a DOI that no OpenAlex record has and prints the fields that matter when you debug.

import asyncio

from bibliofabric import NotFoundError
from bibliofabric.openalex import OpenAlexClient


async def main() -> None:
    async with OpenAlexClient() as client:
        try:
            await client.works.get("10.9999/not-a-real-doi")
        except NotFoundError as error:
            print("type:", type(error).__name__)
            print("status_code:", error.status_code)
            print("message:", error.message)
            print("body:", error.body)


asyncio.run(main())
type: NotFoundError
status_code: 404
message: API request failed with status 404
body: {'error': 'Not Found', 'message': 'Work doi:10.9999/not-a-real-doi not found'}

Credential query parameters stay out of exception text: the client scrubs them before it builds the message, so a leaked log line cannot carry a key.

Retries happen without your code

A get() call makes up to four attempts: the first try plus max_retries retries, three by default. A failed attempt is retried when the HTTP method is idempotent (GET, HEAD, OPTIONS, PUT, DELETE) and one of these happened:

  • the API answered 429, 500, 502, 503, or 504
  • the connection failed (NetworkError)
  • the request timed out (TimeoutError)

The wait between attempts honors a Retry-After header, in seconds or as an HTTP date, capped at max_retry_wait (60 seconds). Without that header the client uses jittered exponential backoff with the same cap. When the last attempt still fails, the exception reaches your code, and RateLimitError carries the last Retry-After value in .retry_after.

Pass retry=False to client.request() to disable retries for one call, or retry=True to retry a non-idempotent call such as a read-only POST batch request. For clients with OAuth tokens, a 401 triggers one automatic token refresh and retry before AuthError is raised.

Skip bad records during a harvest

By default, one record that fails validation stops the harvest with ValidationError. Pass on_error="skip" and a list, and the search methods (search, iterate, collect, first, batch_get) drop the bad record and append the ValidationError to your list instead; the untouched payload is on the exception as .raw.

import asyncio

from bibliofabric.openalex import OpenAlexClient


async def main() -> None:
    async with OpenAlexClient() as client:
        failures = []
        works = await client.works.collect(
            {"publication_year": 2024, "is_oa": True},
            limit=10,
            on_error="skip",
            failures=failures,
        )
        print("collected:", len(works), "works")
        print("skipped:", len(failures), "records")


asyncio.run(main())
collected: 10 works
skipped: 0 records

The list stayed empty because every record validated. Each ValidationError in failures keeps the untouched payload in .raw, which is what you need to report a model gap.

Client-side rate limits

The limiter in every client spaces requests and bounds how many run at once. Three settings control it, and each client ships defaults that match what its API tolerates:

Client Default pace (requests/s) Default concurrency
arXiv 1/3 1
Crossref 3 3
DataCite 1.5 3
DOAJ 1 2
DOI 2 2
Europe PMC 3 2
ISSN Portal 1 2
OpenAlex 10 (semantic search 1) 5
OpenAIRE 2 (Scholix 1) 4
OpenCitations 3 3
ORCID 4 4
ROR 6 5
bioRxiv and medRxiv 1 1
Semantic Scholar 1 1
Wikidata 2 1
Zenodo 2 5

max_requests_per_second sets the overall pace, max_concurrency bounds requests in flight, and rate_limits assigns a pace to a class of requests that a client routes separately, such as OpenAlex semantic search or OpenAIRE Scholix. Set a class to None to remove its cap. After a response, the OpenAlex and Crossref clients expose the rate-limit headers the API sent as the read-only client.last_rate_limit_headers.

Three clients have limits that the API controls, and their pages document the details: Crossref (polite pool and CROSSREF_MAILTO), OpenAlex (keyed access and the daily budget 429), and OpenAIRE (anonymous versus registered quota). The Semantic Scholar page covers its shared keyless pool, which answers 429 when busy.

When a record fails validation

ValidationError means the API answered, but the payload did not fit the model. The exception carries the untouched payload in .raw, the pydantic error in .error, and the model name in .model_name. You can wrap your own payload with validate_model to get the same exception:

from bibliofabric import validate_model, ValidationError
from bibliofabric.crossref.models import Journal

try:
    validate_model(Journal, {"title": 5})
except ValidationError as error:
    print("model:", error.model_name)
    print("raw:", error.raw)
    print("first message:", error.error.errors()[0]["msg"])
model: Journal
raw: {'title': 5}
first message: Input should be a valid list

A get() call raises the same exception, with the request and response attached, when the answer carries none of the keys that the model declares. What the models accept and where the raw JSON lives on a model is covered in Results and models.