Wikibase/API

From mediawiki.org
This page is a translated version of the page Wikibase/API and the translation is 33% complete.
Outdated translations are marked like this.
Версія MediaWiki:
1.9

Що таке Wikibase API?

Wikibase забезпечує загальний механізм зберігання тверджень як структурованих даних. Твердження щодо елементів розміщуються на сервері за адресою wikidata.org. Докладнішу інформацію про Wikibase та інші поняття див. Вікідані:Глосарій.

A statement

The Wikibase API allows querying, adding, removing and editing information on Wikidata or any other Wikibase instance.

Wikibase API надається через набір розширень для модулів API MediaWiki. Отже, щоб використовувати API Wikibase, ви повинні добре знати MediaWiki Action API: дії, запити тощо, а також загальні параметри, такі як 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: Параметр мови фільтрує назви (labels) та описи в діях get або визначає конкретну мову для набору дій.
  • format: Потрібно завжди встановлювати значення json (або jsonfm for debugging), або xml (або xmlfm for debugging). Жодна інша форма не підтримується.
  • 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
}

Відповідь на запит зазвичай міститиме:

  • Ключ success із зведенням boolean до цілого числа, якщо запит успішний. Якщо ціле число дорівнює нулю, будь-які додаткові значення можуть бути помилковими.
  • An error key with an object of two, optionally three keys, code, info and *, if the request is unsuccessful.
  • Інформація про дію. Інформація передається або на верхньому рівні, або в розділі item, якщо це один елемент, або items, якщо їх кілька. Якщо є декілька елементів, кожен знаходиться за ключем зі своїм ідентифікатором елемента.

Порожні об'єкти повертаються як масиви JSON, а не як об'єкти, тоді як порожні параметри видаляють фактичний запис із елемента.

Документація API та модулі Wikibase

Source-generated documentation for the MediaWiki Action API including Wikibase 'wb' API modules is available at wikidata.org/w/api.php

Meta submodules

  • wikibase: ⧼Apihelp-query+wikibase-description⧽
  • wbcontentlanguages: Виводить інформацію про контентні мови, які приймає Вікібаза в різних контекстах.

Property submodules

  • pageterms: ⧼Apihelp-query+pageterms-description⧽
  • wbentityusage: ⧼Apihelp-query+wbentityusage-description⧽

API modules

Можливі помилки

Можливі помилки для будь-якого модуля можна знайти за допомогою action=paraminfo&modules=modulename. The error format corresponds to that of the MediaWiki Action API. See API:Errors and warnings#Legacy format.

All error messages from the Wikibase modules should be internationalised (i18n) and localised (l10n). The user language for the logged-in user will be the default for error messages, but you can override this by adding uselang=languageCode to the URL query string.

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 the pageterms property submodule to get some Wikidata information about pages on the local wiki.
  • The calender models that can be used with Wikibase are the Gregorian calendar(d:Q1985727) and the Julian calendar(d:Q1985786).
  • The API uses revision ids for edit collision detection. If there is an edit collision, the requester must acquire a newer revision id to be able to continue. This typically involves requesting wbgetentities for the item in question, and then storing (and using) the revision from the entry.
  • Any MediaWiki installation can run Wikibase. On the Wikimedia cluster, most wikis do not run the full set of Wikibase extensions.

Wikimedia Commons has its own Wikibase for properties of the files on Commons.

  • Do not test the info value for a particular error, instead use the code value as this will remain independent of localisation.

Див. також