Entities
client.entities wraps the wbgetentities module of the MediaWiki Action API. It returns one entity, a batch, or a long id list, typed as Entity. The examples on this page use the client from the first block; later
blocks reuse it.
import asyncio
from bibliofabric.wikidata import WikidataClient
client = WikidataClient()
wbgetentities and wbsearchentities share this resource, so search(), iterate(), collect(), and first() search entities by label on the same object, and count() raises ConfigurationError because search answers carry no total. Search text belongs to Search, and id lists to iterate_ids() below.
Get one entity
entity = await client.entities.get("Q42", select=["labels", "descriptions"])
print(entity.id, entity.type)
print("description:", entity.description())
same = await client.entities.get("https://www.wikidata.org/wiki/Q42", select=["labels"])
print("url form:", same.id)
print("exists:", await client.entities.exists("Q42"))
Q42 item
description: British science fiction writer and humorist (1952
url form: Q42
exists: True
The output above trims the description, which ends with the years Douglas Adams lived. Upstream quirk: Q42 currently answers no English label in any read shape, so entity.label() returns None; see upstream quirks.
The id accepts Q, P, and L ids in any letter case, the wiki URL form, and the entity URL form. The prefix letter is required. A bare number such as "42" raises
ConfigurationError because the entity type would be guessed, and M
(MediaInfo) ids are rejected. An id the API rejects, and an id it answers
with a missing stub, raise NotFoundError.
Pass entity parts with select= (mapped to the API's props parameter) and the remaining parameters through params:
entity = await client.entities.get(
"Q146",
select=["labels", "descriptions"],
params={"languages": ["en", "de"], "sitefilter": ["enwiki"], "redirects": "no"},
)
print(sorted(entity.labels))
print(entity.labels["de"].value)
print(entity.description())
['de', 'en']
Hauskatze
small domesticated carnivorous mammal
redirects accepts "yes" and "no" (default "yes"). With "no", a redirect id answers as a stub entity with info only.
Get many entities in a batch
batch_get() chunks ids at the API's limit of 50 per request and returns a dict keyed by the normalized id. An id that makes the API reject the whole request (no-such-entity, for example an item number above the highest one), and an id the successful answer omits or answers with a missing stub (a deleted item, an unknown lexeme), raise NotFoundError under the default on_error="raise". With on_error="skip" the client leaves such ids out of the dict and records them in failures.
batch = await client.entities.batch_get(["Q42", "P31", "L1"], select=["labels"])
print(sorted(batch))
for entity_id, item in sorted(batch.items()):
print("batch", entity_id, item.label() or "(no en label)")
keys: ['L1', 'P31', 'Q42']
batch L1 (no en label)
batch P31 instance of
batch Q42 (no en label)
With redirects=yes (the default), a redirect id answers with the entity
of its target. The API keys the entities member by the target and reports
the mapping in its redirects member. The client reads that member, so the
redirected entity stays in the result under the id you asked for, and its
id attribute carries the target id.
Iterate a long id list
iterate_ids() walks an unbounded id list in order, 50 ids per request. Ids are normalized and deduplicated first. An unknown id raises NotFoundError: that covers an id the API rejects with no-such-entity and an id the successful answer omits or answers with a missing stub, such as a deleted item. With on_error="skip" the client drops the id, repeats the request without a rejected one, and records it in failures with its error.
ids = ["Q42", "Q36600", "Q999999999", "P31", "L1"]
failures = []
seen = []
async for entity in client.entities.iterate_ids(
ids, select=["labels"], on_error="skip", failures=failures
):
seen.append(entity.id)
print("seen:", seen)
print("failures:", [failure["id"] for failure in failures])
seen: ['Q42', 'Q36600', 'P31', 'L1']
failures: ['Q999999999']
on_error accepts only "raise" and "skip"; other values raise ConfigurationError before any request. Redirect ids yield the entity of their target.
Get the full entity per format
client.entity_data reads wiki/Special:EntityData/{id}.{format}, which serves the full entity in one serialization without the 50-id limit of wbgetentities.
result = await client.entity_data.get("Q42")
print("id:", result.id, "entity id:", result.entity.id)
print("P31 claims:", len(result.entity.claims.get("P31", [])))
ttl = await client.entity_data.get("Q42", output_format="ttl")
print(ttl.document.content_type, len(ttl.document.text))
id: Q42 entity id: Q42
P31 claims: 1
content_type: text/turtle chars: 733963
get() returns an EntityDataResult. For output_format="json" (the default) the entity field carries the parsed Entity, in the same shape as wbgetentities. For jsonld, rdf, nt, ttl, and n3 the document field carries an EntityDataDocument with the raw text and the answered content_type. Other suffixes answer 415, so output_format is validated on the client side. revision= serves an old revision id; an unknown revision answers 404. A redirect id answers with the entity of its target, resolved through the payload's redirects member, and result.id stays the id you asked for.
negotiate() walks the content-negotiation route. /entity/{id} on the
configured host answers 303 to Special:EntityData based on the Accept
header, and the client follows the redirect.
document = await client.entity_data.negotiate("Q42", accept="text/turtle")
print(document.content_type, len(document.text))
content_type: text/turtle chars: 733963
The Entity model
Entity carries type, id, labels, descriptions, aliases, claims, sitelinks, datatype (properties), and the page metadata (pageid, lastrevid, modified). Claim carries mainsnak, rank, qualifiers, and references; Snak.datavalue keeps the value untyped, so every Wikidata value shape survives. Sitelink carries site, title, badges, and url when sitelinks/urls was requested. Unknown fields are kept (extra="allow"), so lexeme payloads survive validation.