API reference
Generated from the source with mkdocstrings.
Client
bibliofabric.wikidata.WikidataClient
Bases: BaseApiClient
Client for Wikidata: the Action API, the Wikibase REST API, and SPARQL.
The API needs no credentials, but all three services ask for a
descriptive User-Agent with contact information; the client builds it
from the settings. www.wikidata.org serves both the Action API
(w/api.php) and the Wikibase REST API (w/rest.php/wikibase/v1),
so one client covers them. SPARQL lives on query.wikidata.org and is
reached through client.sparql.
entities
cached
property
The wbgetentities resource: get, batch, and iterate ids.
search
cached
property
The wbsearchentities and REST search resources.
claims
cached
property
The wbgetclaims resource.
sitelinks
cached
property
The wbgetentities site link resource.
items
cached
property
The Wikibase REST item routes.
properties
cached
property
The Wikibase REST property routes.
statements
cached
property
The Wikibase REST statement routes.
entity_data
cached
property
The Special:EntityData routes (full entity per format).
lexemes
cached
property
The WikibaseLexeme REST read routes.
utilities
cached
property
The Action API utility read modules (badges, format, parse, suggestions, constraints).
sparql
cached
property
The SPARQL query service on query.wikidata.org.
Sync client
bibliofabric.wikidata.WikidataSyncClient
Bases: SyncBaseApiClient
Client for Wikidata: the Action API, the Wikibase REST API, and SPARQL.
The API needs no credentials, but all three services ask for a
descriptive User-Agent with contact information; the client builds it
from the settings. www.wikidata.org serves both the Action API
(w/api.php) and the Wikibase REST API (w/rest.php/wikibase/v1),
so one client covers them. SPARQL lives on query.wikidata.org and is
reached through client.sparql.
entities
cached
property
The wbgetentities resource: get, batch, and iterate ids.
search
cached
property
The wbsearchentities and REST search resources.
claims
cached
property
The wbgetclaims resource.
sitelinks
cached
property
The wbgetentities site link resource.
items
cached
property
The Wikibase REST item routes.
properties
cached
property
The Wikibase REST property routes.
statements
cached
property
The Wikibase REST statement routes.
entity_data
cached
property
The Special:EntityData routes (full entity per format).
lexemes
cached
property
The WikibaseLexeme REST read routes.
utilities
cached
property
The Action API utility read modules (badges, format, parse, suggestions, constraints).
sparql
cached
property
The SPARQL query service on query.wikidata.org.
Settings
bibliofabric.wikidata.WikidataSettings
Bases: BaseApiSettings
Wikidata-specific client settings.
Inherits timeout, max_retries, max_retry_wait,
max_requests_per_second, max_concurrency, user_agent and
mailto from :class:bibliofabric.config.BaseApiSettings. The API
needs no credentials, but the MediaWiki Action API, the Wikibase REST
API, and the SPARQL query service all ask for a descriptive
User-Agent with contact information: effective_user_agent()
builds it from user_agent or the package metadata, and mailto
is appended when it is set.
Resource clients
The entities and search resources inherit the generic operations from bibliofabric.ResourceClient (get, search, iterate, collect, first, count) through bibliofabric.wikidata._async.base.WikidataResourceClient. Only the members that Wikidata changes or adds are shown here.
bibliofabric.wikidata._async.entities.EntitiesClient
Bases: WikidataResourceClient[Entity]
Client for the wbgetentities module.
The API answers at most 50 ids per request (toomanyvalues above 50,
verified on 2026-11-27). :meth:batch_get chunks through
:class:~bibliofabric.ResourceClient; :meth:iterate_ids walks an
unbounded id list one chunk at a time, in order. wbgetentities has
no search route, so search(), iterate(), collect(),
first(), and count() raise ConfigurationError; use
client.search for search text and iterate_ids() for id lists.
:meth:exists fetches through :meth:get because the API has no HEAD
route.
get(id, *, select=None, params=None)
async
Fetch one entity; 404 (no-such-entity) raises NotFoundError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str | int
|
Entity id ( |
required |
select
|
Sequence[str] | None
|
Pass entity parts as |
None
|
params
|
Mapping[str, Any] | None
|
Raw |
None
|
iterate_ids(ids, *, props=None, languages=None, sitefilter=None, on_error='raise', failures=None)
Iterate over many ids, fetching up to 50 per request, in order.
Ids are normalized and deduplicated first. An id the API does not
know raises NotFoundError; with on_error="skip" it is dropped
and recorded in failures instead. props, languages, and
sitefilter pass through to wbgetentities. A redirect id
yields the entity of its target.
_fetch_batch_chunk(field, chunk, *, select=None)
async
Fetch one id chunk.
An id that the API answers with a missing stub (a deleted item,
an unknown lexeme or property) is absent from the result, as the
:meth:batch_get contract says. An id that makes the API reject the
whole request (no-such-entity) raises NotFoundError. A
redirect id answers with the record of its target, keyed through the
redirects member, and stays in the result.
bibliofabric.wikidata._async.search.SearchClient
Bases: WikidataResourceClient[EntitySearchResult]
Client for entity and property search.
search() uses wbsearchentities; search_items() and
search_properties() use the Wikibase REST API, whose answers carry a
language-fallback display label. wbsearchentities reports no total,
so count() is not supported; iterate() walks continue offset
pages until the API returns an empty page. The module has no per-id
route, so get(), exists(), and batch_get() raise
ConfigurationError.
search(filters=None, *, query=None, language=None, uselang=None, type=None, strict_language=None, sort=None, select=None, page=None, page_size=None, cursor=None, on_error='raise', failures=None, params=None)
async
Search entities by label and alias in language.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str | None
|
The search text. |
None
|
language
|
str | None
|
Code to search in (default |
None
|
uselang
|
str | None
|
Language of the result labels (default |
None
|
type
|
str | None
|
|
None
|
strict_language
|
bool | None
|
Search only in |
None
|
params
|
Mapping[str, Any] | None
|
Raw |
None
|
count(filters=None, *, query=None, params=None)
async
Not supported: wbsearchentities reports no total.
search_items(query, *, language='en', limit=None, offset=None)
async
Search items through the REST route /search/items.
search_properties(query, *, language='en', limit=None, offset=None)
async
Search properties through the REST route /search/properties.
suggest_items(query, *, language='en', limit=None, offset=None)
async
Suggest items through the REST route /suggest/items.
The suggester answers the same result shape as /search/items
and matches aliases too; its query parameter is q (verified
2026-11-28).
suggest_properties(query, *, language='en', limit=None, offset=None)
async
Suggest properties through the REST route /suggest/properties.
bibliofabric.wikidata._async.claims.ClaimsClient
Client for the claims of one entity via wbgetclaims.
For full entity payloads with claims included, prefer
:attr:WikidataClient.entities; wbgetclaims filters the claims of
one entity by property and rank.
__init__(client)
Build the resource client on a WikidataClient.
get(id, *, property=None, rank=None)
async
Return the claims of id, keyed by property id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Entity id ( |
required |
property
|
str | None
|
Restrict to one property ( |
None
|
rank
|
str | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
ClaimsByProperty
|
A dict of property id to the :class: |
ClaimsByProperty
|
records. An entity without claims answers |
bibliofabric.wikidata._async.sitelinks.SitelinksClient
Client for the site links of an item.
Site links travel inside wbgetentities payloads; this client reads
only the sitelinks part so a caller can fetch them without the rest
of the entity.
__init__(client)
Build the resource client on a WikidataClient.
get(id, *, sites=None, with_urls=False)
async
Return the site links of id, keyed by site id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Item id ( |
required |
sites
|
Sequence[str] | str | None
|
Optional site filter ( |
None
|
with_urls
|
bool
|
Include the resolved article URL per link by asking
for the |
False
|
Returns:
| Type | Description |
|---|---|
SitelinkMap
|
A dict of site id to :class: |
SitelinkMap
|
without site links answers |
bibliofabric.wikidata._async.rest_items.ItemsClient
Client for the REST item routes under /entities/items.
The REST payload differs from wbgetentities: labels and descriptions
are language-to-string maps, aliases are language-to-list-of-strings
maps, and each term route answers one language with a fallback chain.
__init__(client)
Build the resource client on a WikidataClient.
description(id, language)
async
Return the item description in language (no fallback chain).
description_with_fallback(id, language)
async
Return the item description in language or a fallback language.
get(id)
async
Return the full REST item for id.
A property or lexeme id raises ConfigurationError: the item
routes never serve other entity kinds. The _fields parameter the
OpenAPI document lists is rejected by the live API with
invalid-query-parameter (verified on 2026-11-27), so full
payloads are the only option.
label(id, language)
async
Return the item label in language (no fallback chain).
label_with_fallback(id, language)
async
Return the item label in language or a fallback language.
The fallback route answers 307 and the redirect target answers the
plain value string, so this method returns str.
sitelink(id, site)
async
Return one site link of an item.
bibliofabric.wikidata._async.rest_items.PropertiesClient
Client for the REST property routes under /entities/properties.
__init__(client)
Build the resource client on a WikidataClient.
datatypes()
async
Return /property-data-types: data type id to value type id.
get(id)
async
Return the full REST property for id.
An item or lexeme id raises ConfigurationError: the property
routes never serve other entity kinds.
bibliofabric.wikidata._async.statements.StatementsClient
Client for the REST statement routes.
Statements exist in two shapes. This client serves the REST shape
({"type": ..., "content": ...} values, list qualifiers); the Action
API shape lives in :attr:WikidataClient.entities and
:attr:WikidataClient.claims.
__init__(client)
Build the resource client on a WikidataClient.
for_entity(id, *, property=None)
async
Return the statements of an item or property, keyed by property id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Item id ( |
required |
property
|
str | None
|
Restrict to one property id through the |
None
|
get(statement_id)
async
Return one statement by its id (Q42$F078E5B3-...).
Statement ids carry $; an id without one raises
ConfigurationError. The $ is URL-encoded in the route.
bibliofabric.wikidata._async.entity_data.EntityDataClient
Client for Special:EntityData and the /entity/{id} resolver.
__init__(client)
Build the resource client on a WikidataClient.
get(id, *, format=JSON_FORMAT, revision=None)
async
Fetch the full entity in one serialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Entity id ( |
required |
format
|
str
|
One of |
JSON_FORMAT
|
revision
|
int | None
|
Serve this revision id instead of the current one. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
EntityDataResult
|
class: |
EntityDataResult
|
carries the parsed :class: |
|
EntityDataResult
|
|
|
EntityDataResult
|
and content type for the RDF formats. |
negotiate(id, *, accept, revision=None)
async
Fetch the entity through /entity/{id} content negotiation.
/entity/{id} on the main host answers 303 to
Special:EntityData/{id}.{format} based on the Accept header;
this method follows the redirect.
bibliofabric.wikidata._async.lexemes.LexemesClient
Client for the REST lexeme routes.
__init__(client)
Build the resource client on a WikidataClient.
get(id)
async
Return the full REST lexeme for id (lemmas, forms, senses).
Only L ids serve the lexeme route, so any other id raises
ConfigurationError before a request is sent.
bibliofabric.wikidata._async.utilities.UtilitiesClient
Client for the Action API utility read modules.
__init__(client)
Build the resource client on a WikidataClient.
available_badges()
async
Return every badge id usable on site links (wbavailablebadges).
check_constraints(ids, *, claim_ids=None, constraint_ids=None, statuses=None)
async
Check constraint compliance of entities (wbcheckconstraints).
The module's entity parameter is id (verified 2026-11-28);
entity or entityid answer the no-data error. Each
result carries the claim id, the constraint, and the check status
per claim. At most 50 ids fit one request, so longer lists are sent
in chunks and the reports merge.
format_entities(ids)
async
Return HTML links per id (wbformatentities).
Ids are normalized and sent in chunks of 50, the Action API's
multi-value limit. The module ignores props and languages
with a warning (verified 2026-11-27), so they are not offered here.
format_value(datavalue, datatype)
async
Return the HTML rendering of one datavalue (wbformatvalue).
datavalue is the {"type": ..., "value": ...} shape; the
service answers baddatavalue without the type key.
parse_value(values, *, datatype)
async
Parse serialized values against a datatype (wbparsevalue).
suggestions(*, entity=None, properties=None, types=None, language=None, limit=None, continuation=None)
async
Return property suggestions (wbsgetsuggestions).
The module answers an error unless entity or properties is
given (verified 2026-11-27), so neither being set raises
ConfigurationError before a request is sent. At most 50
properties fit one request, so longer lists are sent in chunks
and the suggestions concatenate in order.
bibliofabric.wikidata._async.sparql.SparqlClient
Client for SPARQL SELECT, ASK, and CONSTRUCT queries.
The query service is a second host, so the
:class:WikidataQueryClient behind this resource is a second API
client instance. It shares the settings object and the rate limiter with
the main client: SPARQL requests run in the sparql rate class, Action
API and REST requests in the default class, and one limiter inside
the main client paces both classes. See docs/wikidata/sparql.md.
The service answers malformed or overlong queries with HTTP 400 and a
plain-text Java stack trace; those raise
:class:~bibliofabric.exceptions.APIError with the text as the body.
__init__(query_client)
Build the resource client on the second-host query client.
query(query, *, timeout=None)
async
Run a query with GET and return the typed SPARQL 1.1 JSON result.
A SELECT answer carries results; an ASK answer carries
boolean.
query_post(query, *, timeout=None)
async
Run a query with POST and return the typed SPARQL 1.1 JSON result.
Long queries belong in a POST body: URL length limits do not
apply. The POST is read-only, so the request carries retry=True
for the framework's transient-failure retries.
query_text(query, *, format='json', timeout=None)
async
Run a query with GET and return the raw body as text.
format selects the representation through the Accept header:
the service ignores a non-JSON format query parameter and answers
SPARQL-result XML unless asked otherwise (verified 2026-11-27).
Supported values: json, xml, csv, tsv, turtle.
The body passes through as text; only :meth:query and
:meth:query_post parse the typed SPARQL 1.1 JSON shape.
Helpers and dialect
bibliofabric.wikidata.normalize_wikidata_id(value)
Return the bare canonical Wikidata id (Q42, P31, L1).
Accepts the id itself (any letter case), the wiki URL form
(https://www.wikidata.org/wiki/Q42), and the entity URL form
(https://www.wikidata.org/entity/Q42). The id must carry its
Q/P/L prefix: a bare number ("42") is rejected because
the entity type would be guessed. Raises
:class:~bibliofabric.exceptions.ConfigurationError for anything else.
bibliofabric.wikidata.dialect
Query dialect and endpoint paths for Wikidata.
All requests go to two hosts. www.wikidata.org serves both the MediaWiki
Action API (w/api.php) and the Wikibase REST API
(w/rest.php/wikibase/v1), so one client with one rate limiter covers
both. The SPARQL query service lives on query.wikidata.org and is served
by a second client instance that shares the settings object and the limiter
through the sparql rate class.
ACTION_API_BASE_URL = 'https://www.wikidata.org'
module-attribute
Base URL of the Action API and REST API host.
ACTION_PATH = 'w/api.php'
module-attribute
Path of the MediaWiki Action API on www.wikidata.org.
MAX_IDS_PER_REQUEST = 50
module-attribute
MAX_SEARCH_LIMIT = 50
module-attribute
REST_PREFIX = 'w/rest.php/wikibase/v1'
module-attribute
Path prefix of the Wikibase REST API on www.wikidata.org.
SPARQL_BASE_URL = 'https://query.wikidata.org'
module-attribute
Base URL of the SPARQL query service host.
SPARQL_PATH = 'sparql'
module-attribute
Path of the SPARQL endpoint on query.wikidata.org.
WIKIDATA_DIALECT = QueryDialect(page_size_param='limit', max_page_size=MAX_SEARCH_LIMIT, default_page_size=MAX_SEARCH_LIMIT, iterate_page_size=MAX_SEARCH_LIMIT, count_page_size=1, page_param=None, offset_param='continue', cursor_param=None, sort_param=None, query_param='search', select_param=None)
module-attribute
bibliofabric.wikidata.unwrapper.WikidataUnwrapper
Extracts results, totals, and metadata from Action API JSON.
item(body, *, request=None, response=None)
Return the single entity of a one-id wbgetentities response.
An unknown lexeme or property id answers with a missing stub
instead of an error, which raises NotFoundError here.
meta(body, *, request=None, response=None)
Return the envelope minus search (searchinfo, success).
next_cursor(body, *, request=None, response=None)
Return None; search pages by continue offset, not cursor.
results(body, *, request=None, response=None)
Return the search records of a wbsearchentities response.
total(body, *, request=None, response=None)
Return None; wbsearchentities reports no total.
Models
The models live in bibliofabric.wikidata.models and are re-exported from the top-level package. They are plain Pydantic models with extra="allow".
bibliofabric.wikidata.models.Entity
Bases: _WikidataModel
One entity as returned by wbgetentities.
Items carry labels, descriptions, aliases, claims, and
sitelinks. Properties carry datatype and the term fields. Lexemes
and forms carry their own shapes, which extra="allow" keeps.
label(language='en')
Return the label in language, or None when there is none.
description(language='en')
Return the description in language, or None.
bibliofabric.wikidata.models.Term
Bases: _WikidataModel
One language-qualified label, description, or alias.
bibliofabric.wikidata.models.Claim
Bases: _WikidataModel
One statement of a Wikidata entity as returned by the Action API.
bibliofabric.wikidata.models.Snak
Bases: _WikidataModel
One claim, qualifier, or reference snak.
bibliofabric.wikidata.models.DataValue
Bases: _WikidataModel
The datavalue member of a snak.
value carries one of the Wikidata value shapes (a string, an entity
id object, a time object, a quantity object, a globe-coordinate object,
or a monolingual-text object) depending on type. The client keeps it
untyped so no payload shape is lost; client.utilities.parse_value
parses serialized values back into these shapes.
bibliofabric.wikidata.models.Reference
Bases: _WikidataModel
The reference block of a claim.
bibliofabric.wikidata.models.Sitelink
Bases: _WikidataModel
One site link of an item.
bibliofabric.wikidata.models.EntitySearchResult
Bases: _SearchModel
One hit of a wbsearchentities response.
bibliofabric.wikidata.models.RestItem
Bases: _RestModel
An item in the REST shape (/entities/items/{item_id}).
label(language='en')
Return the label in language, or None when there is none.
description(language='en')
Return the description in language, or None.
bibliofabric.wikidata.models.RestProperty
Bases: _RestModel
A property in the REST shape (/entities/properties/{property_id}).
label(language='en')
Return the label in language, or None when there is none.
bibliofabric.wikidata.models.RestStatement
Bases: _RestModel
One statement in the REST shape.
bibliofabric.wikidata.models.RestQualifier
Bases: _RestModel
One qualifier or reference part in the REST shape.
bibliofabric.wikidata.models.RestReference
Bases: _RestModel
One reference block of a REST statement.
bibliofabric.wikidata.models.RestSitelink
Bases: _RestModel
One site link in the REST shape.
bibliofabric.wikidata.models.RestSearchResult
Bases: _RestModel
One hit of /search/items or /search/properties.
display_label is None when the hit has no label in any fallback
language.
bibliofabric.wikidata.models.SparqlResult
Bases: _SparqlModel
A typed SPARQL 1.1 JSON result as the query service answers format=json.
A SELECT answer carries results; an ASK answer carries
boolean instead. Exactly one of the two is present.
rows()
Return the bindings as plain variable -> value strings.
An ASK answer has no bindings, so this returns [].
bibliofabric.wikidata.models.SparqlBindingValue
Bases: _SparqlModel
One typed term of a result row.
type is one of uri, literal, bnode (SPARQL 1.1 JSON),
plus the Wikidata extensions literal-ext and unknown. Literal
terms carry xml:lang for language-tagged literals and datatype
(an XSD datatype IRI) for typed ones.
bibliofabric.wikidata.models.EntityDataResult
Bases: _MiscModel
The typed result of an EntityData read.
entity is set for format="json"; document is set for the RDF
formats. Exactly one of the two carries the payload.
bibliofabric.wikidata.models.EntityDataDocument
Bases: _MiscModel
A non-JSON Special:EntityData document (an RDF serialization).
The RDF formats (jsonld, rdf, nt, ttl, n3) pass through as
text; format is the requested suffix and content_type is the
Content-Type the service answered with.
bibliofabric.wikidata.models.RestLexeme
Bases: _RestModel
A lexeme in the REST shape (wikibaselexeme/v0/entities/lexemes/{id}).
lexical_category and language are bare item ids here, unlike the
wbgetentities lexeme payload where they are nested objects.
bibliofabric.wikidata.models.ParsedValue
Bases: _MiscModel
One parsed value of wbparsevalue.
bibliofabric.wikidata.models.PropertySuggestion
Bases: _MiscModel
One suggestion of wbsgetsuggestions.
bibliofabric.wikidata.models.CheckedClaim
Bases: _MiscModel
The constraint checks of one claim.