Wikibase/API

From MediaWiki.org
Jump to: navigation, search

Other languages:
català • ‎Deutsch • ‎English • ‎español • ‎suomi • ‎français • ‎italiano • ‎日本語 • ‎Nederlands • ‎polski • ‎português • ‎português do Brasil • ‎русский • ‎Türkçe
Tools clipart.png This page is part of the MediaWiki PHP action API documentation.
MediaWiki APIsAPI:Main page

MediaWiki PHP action API

v · d · e
MediaWiki version: 1.9

Note Note: Please see wikidata.org/w/api.php for comprehensive up-to-date MediaWiki API documentation, including Wikibase 'wb' API modules, generated from source.

General introduction[edit | edit source]

The Wikibase API is provided by a set of extensions that implement MediaWiki API modules. So to use it you should have basic familiarity with the MediaWiki web API: actions, queries, etc., and conversely all your experience with generic parameters such as curtimestamp and requestid, etc. applies to the Wikibase API.

Wikibase and Wikidata[edit | edit source]

Wikibase provides a general mechanism to store statements as structured data. Any MediaWiki installation can run it. Wikidata statement.svg

(See wikidata:Glossary for explanations of these terms.) On the Wikimedia cluster, most wikis do not runs the full set of Wikibase extensions. The statements about items live on the server wikidata.wikimedia.org. Since this includes statements about the millions of items in Wikipedias, it's a fantastic resource to query!

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

The extensions implement the action=query submodules

  • pageterms query property submodule
  • wikibase query meta submodule0

and the API modules

  • wbavailablebadges
  • wbcreateclaim
  • wbcreateredirect
  • wbeditentity
  • wbformatvalue
  • wbgetclaims
  • wbgetentities
  • wblinktitles
  • wbmergeitems
  • wbparsevalue
  • wbremoveclaims
  • wbremovequalifiers
  • wbremovereferences
  • wbsearchentities
  • wbsetaliases
  • wbsetclaim
  • wbsetclaimvalue
  • wbsetdescription
  • wbsetlabel
  • wbsetqualifier
  • wbsetreference
  • wbsetsitelink
  • wbsgetsuggestions

To generate API documentation for just one of these modules, append /wbmoduleName to Special:ApiHelp; for example visit Special:ApiHelp/wbgetentities.

To generate API documentation for multiple modules on one page, pass module names separated by | as the submodules parameter to api.php?action=help&submodules...; for example, this URL generates the documentation for all the modules listed above.

Wikibase clients[edit | edit source]

Many Wikimedia wikis (but as of February 2015, not www.mediawiki.org) run the Extension:Wikibase Client extension. This lets API clients on them

  • query the wikibase meta submodule to determine URLs for the full Wikibase repo see its API help
  • query the the pageterms property submodule to get some Wikidata information about pages on the local wiki

Post vs. get[edit | edit source]

  • Requests that change content should use a token.
  • Requests should use HTTP POST or GET requests according to api module. Modules that change content use POST. Use POST to avoid problem with non-behaving proxies.
  • Clients should be aware of and handle errors from the API.

Module parameters[edit | edit source]

There are some parameters that are nearly always available. Plural forms are used in those cases where a parameter can take several values.

id | ids 
Identifies a specific entity or entities, most typical an item. Plural form is used in wbgetentities.
site ∩ title | sites ∩ titles 
Identifies a single item or multiple items. Plural form is used in wbgetentities. Only one of sites and titles can have multiple values at the same time.
language | languages 
The language is used as a filter mechanism to filter labels and descriptions in get actions or to identify a specific language for set actions.
format 
Should always be set to json (or jsonfm for debugging), or xml (or xmlfm for debugging), no other form is supported.
summary 
Adds a user specified summary instead of the system generated one. If not provided the module will generate its own summary, and if this fails the item itself will provide a summary.
token 
An encrypted string the requester must pass on shall the request be fulfilled.
baserevid 
An id for the last known revision that must be passed on shall the server be able to detect edit collisions.

Normally the return value either has a success key with a boolean cast as an integer or an error key with an object of two, optionally three, keys code, info and "*". The last one is additional information. Information about the action is either passed on the top level or under item if its one single item or items if its several. If it is several items each is found under a key with its own item id. See #Success and #Errors.

  • Note that empty objects are returned as json arrays and not as objects.
  • Note that empty parameters removes the actual entry from the item.

Modules[edit | edit source]

wbgetentities[edit | edit source]

Module to get the content of several entities, possibly with only parts of the entity included. Entities that are checked for existence, but not found, are reported (bugzilla:45509). During lookup both sites and titles can be a list, that is if the entities are items, but the shorter one is cycled to match the longer one. If one of the lists contain a single entry it will be used for all entries from the other list. If both lists are equally long the sitelinks will be well-formed pairs.

getEntities( ( ids XOR ( sites, titles ) ), *props, *languages )
  • ids are numeric identifiers for existing entities, if the entities does not exist they will be marked as missing.
  • sitestitles is pairs that identifies multiple existing entities (only items), if they do not exist they will be marked as missing.
  • props which list to report, possibly filtered by language if they are language specific. Possible values are labels, descriptions, sitelinks, claims, datatype, aliases. Note that sitelinks are not language specific.
  • sort
  • dir
  • languages are one or more languages to filter the list against. If it is missing all valid languages are reported.
  • languagefallback Apply language fallback for languages defined in the "languages" parameter
  • normalize Try to normalize the page title against the client site (This only works if exactly one site and one page have been given)
  • ungroupedlist Do not group snaks by property id
Examples

wbeditentity[edit | edit source]

  • id is the numeric identifier for an existing item, if the item does not exist an error is returned.
  • sitetitle is a pair that identifies a single existing item, if the item does not exist an error is returned.
  • data
  • clear is a marker to clear out the complete item and start from scratch.
  • new
Examples

wbsetlabel[edit | edit source]

Module to set a label for a single Wikibase entity.

  • id is the numeric identifier for an existing item, if the item does not exist an error is returned.
  • sitetitle is a pair that identifies a single existing item, if the item does not exist an error is returned.
  • language is the language for the label. The language must be a valid identifier.
  • value is the value of the label
Set the string "Wikimedia" for page with id "Q42" as a label in English language 
api.php?action=wbsetlabel&id=Q42&language=en&value=Wikimedia
Set the English language label to "Earth" for the item with site link enwiki => "Earth" 
api.php?action=wbsetlabel&site=enwiki&title=Earth&language=en&value=Earth

wbsetdescription[edit | edit source]

Module to set a description for a single Wikibase entity.

  • id is the numeric identifier for an existing item, if the item does not exist an error is returned.
  • sitetitle is a pair that identifies a single existing item, if the item does not exist an error is returned.
  • language is the language for the description. The language must be a valid identifier.
  • value is the value of the description.
Set the string "An encyclopedia that everyone can edit" for page with id "Q42" as a description in

English language : api.php?action=wbsetdescription&id=Q42&language=en&value=An%20encyclopedia%20that%20everyone%20can%20edit

Set the string "An encyclopedia that everyone can edit" as a description in English language for

page with a sitelink to enwiki:Wikipedia : api.php?action=wbsetdescription&site=enwiki&title=Wikipedia&language=en&value=An%20encyclopedia%20that%20everyone%20can%20edit

wbsetaliases[edit | edit source]

Module to set, add and remove aliases from items. Aliases are alternate names for the items, that can be queried and used for lookup.

setAliases( ( id XOR ( site, title ) ) OR baserevid, ( add OR remove ) XOR set, *summary )
  • id is the numeric identifier for an existing item, if the item does not exist an error is returned.
  • sitetitle is a pair that identifies a single existing item, if the item does not exist an error is returned.
  • set contains a list of strings that will be used as the new list of aliases. The values are normalized before they are used.
  • add contains a list of additional strings that will be used as aliases. The values are normalized before they are used.
  • remove contains a list of strings that will be removed from the the list of aliases. The values are normalized before they are used.
  • language
Examples

wbsetsitelink[edit | edit source]

Module to define new links to pages at external client sites. During processing of requests the module will query the external site to verify the existence of the page and to acquire the canonical form of the prefix and the pagename.

linkSite( ( id XOR ( site, title ) ) OR baserevid, linksite, linktitle, *summary )
  • id is the numeric identifier for an existing item, if the item does not exist an error is returned.
  • sitetitle is a pair that identifies a single existing item, if the item does not exist an error is returned.
  • linksite is the site id for a client site that will be the target of the new link. The site will be queried during the call.
  • linktitle is the title of the page at the client site that will be the target of the new link. The site will be queried during the call.
  • badges is the list of badges linked to the given sitelink.
Examples

wbgetclaims[edit | edit source]

Module for getting Wikibase claims.

  • entity is Id of the entity from which to obtain claims.
  • property is optional filter to only return claims with a main snak that has the specified property.
  • claim a GUID identifying the claim. Required unless entity is provided.
  • rank is optional filter to return only the claims that have the specified rank. (deprecated, normal, preferred)
  • props which list to report, possibly filtered by language if they are language specific. Note that sitelinks are not language specific.
Examples

wbcreateclaim[edit | edit source]

  • entity is the id of the entity you are adding the claim to.
  • snaktype (value, novalue, somevalue)
  • property is the id of the snaks property.
  • value of snak when creating a claim with a snak that has a value.

Add a claim with a string data value:

'action' => 'wbcreateclaim',
'entity' => 'Q82',
'property' => 'P4',
'snaktype' => 'value',
'value' => '"Cyqi3STlJtEJ"',
'bot' => 1,

Add a claim with a wikibase-item data value:

'action' => 'wbcreateclaim',
'entity' => 'Q82',
'property' => 'P2',
'snaktype' => 'value',
'value' => '{"entity-type":"item","numeric-id":63}',
'bot' => 1,

Add a claim with a time data value:

'action' => 'wbcreateclaim',
'entity' => 'Q82',
'property' => 'P11',
'snaktype' => 'value',
'value' => '{"time":"+00000002010-01-02T00:00:00Z","timezone":0,"before":0,"after":0,"precision":11,"calendarmodel":"http://www.wikidata.org/entity/Q1985727"}',
'bot' => 1,

Add a claim with a globe-coordinate data value:

Note: value parameters "globe" and "precision" are optional. Default for "globe" is "http://www.wikidata.org/entity/Q2" (earth).
'action' => 'wbcreateclaim',
'entity' => 'Q9188',
'property' => 'P625',
'snaktype' => 'value',
'value' => '{"latitude":40.748433,"longitude":-73.985656,"globe":"http://www.wikidata.org/entity/Q2"}',
'bot' => 1,

Add a claim with a quantity data value:

Note: ...
'action' => 'wbcreateclaim',
'entity' => 'Q556',
'property' => 'P1086',
'snaktype' => 'value',
'value' => '...',
'bot' => 1,

wbsetclaim[edit | edit source]

Module for creating or updating an entire Claim.

  • claim a claim in json form
  • index
Example 
api.php?action=wbsetclaim&claim={"id":"q2$5627445f-43cb-ed6d-3adb-760e85bd17ee","type":"claim","mainsnak":{"snaktype":"value","property":"p1","datavalue":{"value":"rand'.rand(1,100).'","type":"string"}}}&baserevid=9042&token=foobar

wbsetclaimvalue[edit | edit source]

Module for setting the value of a Wikibase claim.

  • claim a GUID identifying the claim. Required.
  • snaktype (value, novalue, somevalue).
  • value of snak when setting a claim with a snak that has a value.
Example of setting a claim with GUID 
api.php?action=wbsetclaimvalue&claim=q42$D8404CDA-25E4-4334-AF13-A3290BCD9C0F&snaktype=value&value={"entity-type":"item","numeric-id":1}&token=foobar&baserevid=7201010

wbremoveclaims[edit | edit source]

Module for removing Wikibase claims.

  • claim a GUID identifying the claim.
Example of removing a claim with a GUID 
api.php?action=wbremoveclaims&claim=q42$D8404CDA-25E4-4334-AF13-A3290BCD9C0N&token=foobar&baserevid=7201010

wbsetqualifier[edit | edit source]

Module for creating a qualifier or setting the value of an existing one.

  • claim a GUID identifying the claim. Required.
  • property Id of the snaks property
  • value
  • snaktype
  • snakhash

In this example, p4 is a string property:

'format' => 'json',
'action' => 'wbsetqualifier',
'claim' => 'q2$4554c0f4-47b2-1cd9-2db9-aa270064c9f3',
'property' => 'p4',
'value' => '"GdyjxP8I6XB3"',
'snaktype' => 'value',
'token' => 'f18s833ctn49799614c4o747521237c27+\\'

Add a qualifier with a wikibase-item data value:

'format' => 'json',
'action' => 'wbsetqualifier',
'claim' => 'q2$4554c0f4-47b2-1cd9-2db9-aa270064c9f3',
'property' => 'p2',
'snaktype' => 'value',
'value' => '{"entity-type":"item","numeric-id":63}',
'token' => 'f18s833ctn49799614c4o747521237c27+\\'

Add a qualifier with a time data value:

'format' => 'json',
'action' => 'wbsetqualifier',
'claim' => 'q102865$94797627-7ec6-47fd-9207-b615ccd682eb',
'property' => 'p580',
'snaktype' => 'value',
'value' => '{"time":"-00000000363-01-01T00:00:00Z","timezone":0,"before":0,"after":0,"precision":9,"calendarmodel":"http://www.wikidata.org/entity/Q1985727"}',
'token' => 'f18s833ctn49799614c4o747521237c27+\\'

wbremovequalifiers[edit | edit source]

Module for removing a qualifier from a claim.

  • claim a GUID identifying the claim. Required.
  • qualifiers a hash of the qualifier that should be removed.
Remove qualifier with hash "1eb8793c002b1d9820c833d234a1b54c8e94187e" from claim with GUID of "q42$D8404CDA-25E4-4334-AF13-A3290BCD9C0F" 
api.php?action=wbremovequalifiers&statement=q42$D8404CDA-25E4-4334-AF13-A3290BCD9C0F&qualifiers=1eb8793c002b1d9820c833d234a1b54c8e94187e

wbsetreference[edit | edit source]

Module for creating a reference or setting the value of an existing one.

  • statement a GUID identifying the statement. Required.
  • snaks
  • snaks-order
  • reference a hash of the reference that should be updated.
  • index
action:wbsetreference
format:json
statement:q76$D4FDE516-F20C-4154-ADCE-7C5B609DFDFF
snaks:{"p143":[{"snaktype":"value","property":"p143","datavalue":{"type":"wikibase-entityid","value":{"entity-type":"item","numeric-id":11696}}}]}
baserevid:779
token:+\
action:wbsetreference
format:json
statement:q76$D4FDE516-F20C-4154-ADCE-7C5B609DFDFF
snaks:{"p888":[{"snaktype":"value","property":"p888","datavalue":{"type":"string","value":"00905364"}}}
baserevid:779
token:+\

wbremovereferences[edit | edit source]

Module for removing one or more references of the same statement.

  • statement a GUID identifying the statement. Required.
  • references a hash of the reference that should be updated.
Example of removing a reference with hash from claim with GUID 
api.php?action=wbremovereferences&statement=q42$D8404CDA-25E4-4334-AF13-A3290BCD9C0F&references=455481eeac76e6a8af71a6b493c073d54788e7e9&token=foobar&baserevid=7201010

wbsearchentities[edit | edit source]

Module to search for entities.

  • search is the text string to search for
  • language is the language to search in
  • type is the type of entities to return
  • limit is the maximum number of results to return (default 7)
  • continue offset to continue the query from a previous search
Search for "abc" in English language, with defaults for type and limit 
api.php?action=wbsearchentities&search=abc&language=en&format=jsonfm
Search for "abc" in English language with a limit of 2 
api.php?action=wbsearchentities&search=abc&language=en&limit=2&format=jsonfm
{
    "searchinfo": {
        "search": "abc"
    },
    "search": [
        {
            "id": "q169889",
            "url": "//www.wikidata.org/wiki/Q169889",
            "description": "American broadcast television network",
            "label": "American Broadcasting Company",
            "aliases": [
                "ABC"
            ]
        },
        {
            "id": "q486289",
            "url": "//www.wikidata.org/wiki/Q486289",
            "description": "anarchist support organization",
            "label": "Anarchist Black Cross",
            "aliases": [
                "ABC"
            ]
        },
    ],
    "search-continue": 2,
    "success": 1
}
Search for "alphabet" in English language for type property 
api.php?action=wbsearchentities&search=alphabet&language=en&type=property&format=jsonfm

wblinktitles[edit | edit source]

Module to associate two articles on two different wikis with a Wikibase item.

  • tositetotitle is pair that identifies first sitelink
  • fromsitefromtitle is pair that identifies second sitelink
Add a link "Hydrogen" from the English page to "Wasserstoff" at the German page 
api.php?action=wblinktitles&fromsite=enwiki&fromtitle=Hydrogen&tosite=dewiki&totitle=Wasserstoff

wbmergeitems[edit | edit source]

Module to merge two Wikibase items.

  • fromid is the numeric identifier for the item to merge from
  • toid is the numeric identifier for the item to merge to
  • ignoreconflicts Array of elements of the item to ignore conflicts for, can only contain values of "label" and or "description" and or "sitelink"
Example
api.php?action=wbmergeitems&fromid=Q1&toid=Q2
{
    "from": {
        "id": "Q1",
        "type": "item",
        "lastrevid": 915
    },
    "to": {
        "id": "Q2",
        "type": "item",
        "lastrevid": 916
    },
    "success": 1
}

wbparsevalue[edit | edit source]

Module to parse strings using a backend ValueParser.

  • parser
  • values
  • options
  • api.php?action=wbparsevalue&format=jsonfm&parser=quantity&values=22223
{
    "results": [
        {
            "raw": "22223",
            "value": {
                "amount": "+22223",
                "unit": "1",
                "upperBound": "+22224",
                "lowerBound": "+22222"
            },
            "type": "quantity"
        }
    ]
}

wbformatvalue[edit | edit source]

Module for formatting DataValues.

  • generate
  • datavalue
  • datatype
  • options
  • api.php?action=wbformatvalue&format=json&generate=text/plain&datavalue={"raw": "22223","value":{"amount":"+22223","unit":"1","upperBound":"+22224","lowerBound":"+22222"},"type":"quantity"}&datatype=quantity
{
    "result": "22,223\u00b11"
}

Data values[edit | edit source]

Time[edit | edit source]

Calendar model

Token[edit | edit source]

See also Manual:Edit token.

Revision[edit | edit source]

The API uses revision ids for edit collision detection. If the revision id is known from an previous reply, page load or similar, then pass on the revision to the edit. Without the revision id it is not possible to detect edit collisions in a reliable way. 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.

Errors[edit | edit source]

Possible errors for all modules can be found at /w/api.php?action=paraminfo&modules=modulename, for example wbeditentity

"Expected" errors will will have a standardized form:

example 
api.php?action=blah&format=jsonfm
{
	"servedby": "srv273",
	"error": {
		"code": "unknown_action",
		"info": "Unrecognized value for parameter 'action': blah"
	}
}

The servedby is given unconditionally for error messages, but could be missing for some less than fatal errors. In some cases error messages can be appended to a success and be called warning(s).

All error messages from the Wikibase modules should be internationalized (i18n) and localized (l10n), but note that error messages from the base API system may not be localized. The user language for the logged in user (usually the same as in the web interface) will be the default for error messages. You can override this by supplying uselang=languageCode in the URL query string

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

An internationalized error message that isn't localized as it should will have additional angle brackets.

example 
api.php?action=wbgetentities&titles=ThisPageDoesNotExist&sites=fi&format=jsonfm
{
	"error": {
		"code": "no-such-item",
		"info": "<wikibase-api-no-such-item>"
	}
}

With correctly localized error message the angle brackets will go away and the info string will print out in clear text. Assuming the user is logged in and use English language it will print as something like the following.

{
	"error": {
		"code": "no-such-item",
		"info": "There are no such item to be found"
	}
}

Switching to Norwegian in the Special:Preferences or by appending uselang=no it will change the text of the info string to a localized variant, while the code string remains constant.

{
	"error": {
		"code": "no-such-item",
		"info": "Det finnes ingen slik item"
	}
}

A lot of error messages are not properly localized.

Success[edit | edit source]

Can be removed since all normal calls will return data of some kind, unless there is an error condition.

If a success is achieved it will have the following form when the format=jsonfm

{
	"success": /* int */
}

The interpretation of the value for success can be dependent on the actual parameters in the call, but usually it is a boolean that is type casted to an integer. Its meaning is that every previous tests evaluated to true. If the number is 0 (zero) any additional values might be wrong.

There might be additional values in the structure after a successful call.

See also[edit | edit source]