Wikibase/API
![]() | Эта страница является частью документации по API действий MediaWiki. |
Версия MediaWiki: | ≥ 1.9 |
Что такое Wikibase API?
Wikibase предоставляет общий механизм хранения утверждений в виде структурированных данных. Утверждения об элементах находятся на сервере wikidata.org. Смотрите Wikidata:Glossary для объяснения этих терминов.

The Wikibase API allows querying, adding, removing and editing information on Wikidata or any other Wikibase instance.
Он предоставляется через набор расширений для модулей MediaWiki API.
Так что чтобы использовать его, вам следует быть несколько осведомлёнными на тему сетевого API MediaWiki: действия, query-запросы и так далее, а также с общими параметрами, такими как curtimestamp
и requestid
.
How to use the Wikibase api
Send requests to the API through HTTP, the same as with the MediaWiki Action API. See API:Tutorial#How to use it for information about how to use the MediaWiki Action API.
Request Format
The endpoint for the API is https://wikidata.org/w/api.php.
In the query string, add the action parameter, which tells the API which action to perform. For example, action=wbgetentities
tells the API to get the data for Wikibase entities. For meta and property submodules, use action=query&meta=yourmodule
and action=query&prop=modulename
respectively.
Некоторые параметры доступны практически всегда. Формы множественного числа используются в случаях, когда параметр может принимать список из нескольких значений.
id/ids
: Идентифицирует объект entity или объекты entities, самый типичный объект item. Форма множественного числа доступна в wbgetentities. Списки идентификаторов следует разделять символом пайп.site ∩ title/sites ∩ titles
: Определяет один объект или несколько объектов. Множественное число используется в wbgetentities. Одновременно только один из параметров sites и titles может принимать множественное число.language/languages
: Указанный язык используется для фильтрации меток и описаний в действиях, получающих данные, или для определения конкретного языка в действиях, задающих данные.format
: Допустимые значения — только json (или jsonfm для отладки) и xml (или xmlfm для отладки), другие форматы не поддерживаются.summary
: Добавляет указанное пользователем описание действия в дополнение к описанию, которое сгенерировалось системой.token
: Зашифрованная строка, которую должен передать делающий запрос, чтобы запрос был выполнен.baserevid
: Идентификатор последней известной версии, который должен быть передан, чтобы сервер мог обнаруживать конфликты правок.
A simple query
GET request
Get the item for page "Berlin" on English Wikipedia.
Explanation of each part of the URL:
http://www.wikidata.org/w/api.php
is the main endpoint.action=wbgetentities
tells the API to get the data for Wikibase entities.sites=enwiki
means get the data from English Wikipedia.titles=Berlin
indicates the title of the page to get data from.props=descriptions
indicates properties to get from the entities, in this case the property is the descriptions of the entities.languages=en
means filter the results down to the English language.format=json
indicates JSON output, which is the recommended output format.
Response
{
"entities": {
"Q64": {
"type": "item",
"id": "Q64",
"descriptions": {
"en": {
"language": "en",
"value": "capital and largest city of Germany"
}
}
}
},
"success": 1
}
The response of a request will usually contain:
- A
success
key with a boolean cast as an integer if the request is successful. If the integer is zero, any additional values might be wrong. - An
error
key with an object of two, optionally three keys,code
,info
and*
, if the request is unsuccessful. - Information about the action. The information is either passed on the top level or under item if it is one single item or items if it is several. If it is several items, each is found under a key with its own item id.
- Обратите внимание, что пустые объекты возвращаются как массивы JSON, а не как объекты JSON.
- Обратите внимание, что при указании пустых параметров содержимое самого свойства объекта удаляется.
Документация к API и модули Wikibase
Meta submodules
- wikibase: Получить сведения о клиенте Wikibase и связанном хранилище Wikibase.
- wbcontentlanguages: Returns information about the content languages Wikibase accepts in different contexts.
Property submodules
- pageterms: Get the Викиданные terms (typically labels, descriptions and aliases) associated with a page via a sitelink.
- wbentityusage: Returns all entity IDs used in the given pages.
API modules
- wbgetentities: Получает данные для нескольких сущностей Wikibase.
- wbavailablebadges: Запрашивает доступные элементы-бэджи.
- wbcreateclaim: Создаёт заявления Wikibase.
- wbcreateredirect: Creates Entity redirects.
- wbeditentity: Creates a single new Wikibase entity and modifies it with serialised information.
- wbformatvalue: Форматирует DataValues.
- wbgetclaims: Получает заявления Wikibase.
- wblinktitles: Ассоциирует две страницы на двух разных вики с элементом Wikibase.
- wbmergeitems: Объединяет несколько элементов.
- wbparsevalue: Анализирует значения, используя
ValueParser
. - wbremoveclaims: Удаляет заявления Wikibase.
- wbremovequalifiers: Removes a qualifier from a claim.
- wbremovereferences: Removes one or more references of the same statement.
- wbsearchentities: Searches for entities using labels and aliases.
- wbsetaliases: Sets the aliases for a Wikibase entity.
- wbsetclaim: Creates or updates an entire Statement or Claim.
- wbsetclaimvalue: Sets the value of a Wikibase claim.
- wbsetdescription: Sets a description for a single Wikibase entity.
- wbsetlabel: Sets a label for a single Wikibase entity.
- wbsetqualifier: Creates a qualifier or sets the value of an existing one.
- wbsetreference: Creates a reference or sets the value of an existing one.
- wbsetsitelink: Associates a page on a wiki with a Wikibase item or removes an already made such association.
- wbsgetsuggestions: Модуль API для получения предложений дополнительных свойств, которые можно добавить к сущности Викибазы. Модуль API предназначен в первую очередь для того, чтобы его мог использовать виджет предложений при редактировании участниками сущности Викибазы.
- wbcheckconstraints: Performs constraint checks on any entity you want and returns the result.
- wbcheckconstraintparameters: Checks the constraint parameters of constraint statements.
Возможные ошибки
Возможные ошибки для всех модулей можно найти, используя action=paraminfo&modules=modulename
.
The error format corresponds to that of the MediaWiki Action API. See API:Errors and warnings#Legacy format.
Все сообщения об ошибках в модулях Wikibase должны быть интернационализованы (i18n) и локализованы (l10n). Язык текущего вошедшего в учётную запись пользователя будет использоваться по умолчанию в сообщениях об ошибках, но вы можете переопределить язык, добавив uselang=languageCode
в URL-строке запроса.
Error type | Code | Info |
---|---|---|
An internationalized error message that isn't localized. | no-such-item | <wikibase-api-no-such-item> |
A correctly localized error message. | no-such-item | There are no such item to be found |
A localized variant.(Norwegian) | no-such-item | Det finnes ingen slik item |
Additional notes
- Many Wikimedia wikis run the Wikibase Client extension. This lets API clients on them to query the
wikibase
meta submodule to determine URLs for the full Wikibase repo, and thepageterms
property submodule to get some Wikidata information about pages on the local wiki.
- С Wikibase могут использоваться Григорианская(d:Q1985727) и Юлианская(d:Q1985786) модели календарей.
- API использует идентификаторы версий для обнаружения конфликтов редактирования. Если конфликт редактирования уже обнаружен, запрашивающий должен получить идентификатор более новой версии, чтобы получить возможность продолжить. Для этого обычно запрашивается
wbgetentities
для соответствующей записи, а из ответа считывается (и используется) идентификатор версии. - Wikibase может использоваться в каждой системе MediaWiki. На кластере Викимедиа, большинство вики не выполняют весь набор расширений Wikibase. Викисклад обладает собственным Wikibase для свойств файлов.
- Do not test the
info
value for a particular error, instead use thecode
value as this will remain independent of localization.
См. также
- API:Главная страница - Руководство для быстрого начала работы с MediaWiki Action API.
- API:FAQ - Часто задаваемые вопросы о MediaWiki Action API.
- API:Tutorial - Самоучитель о том, как использовать MediaWiki Action API.
- Скачать дампы базы Викиданных в форматах JSON (рекомендуется), XML и RDF.