roipoussiere
roipoussiere

Reputation: 5936

MediaWiki API: Get the category tree

I would like to get the to category tree in JSON format using the MediaWiki API.

For instance, here is a category named "Story" in the Game of thrones wiki.

This category have several subcategories, such as Characters, and this last have also sub categories such as Major Characters.

Is it possible to have the category tree of all categories of the wiki?

All the categories are listed here, but:

Upvotes: 1

Views: 1250

Answers (1)

roipoussiere
roipoussiere

Reputation: 5936

Well, I have the solution (by using several queries).

From the man page (http://your_wiki.fr/api.php):

  • list=allcategories returns all the categories of the wiki ;
  • prop=categoryinfo returns informations about a category, including the number of sub-categories.

We first need to choose the 'root' category where the tree begins. I my case, it is "Story".

Then, by using a generator, we can have, for a given category:

  • all its sub-categories,
  • the number of sub-categories of each sub-category.

Here with the Game Of Thrones wikia:

http://gameofthrones.wikia.com/api.php?action=query&generator=categorymembers&gcmtitle=Category:Story&gcmtype=subcat&gcmlimit=500&prop=categoryinfo


Well, now we just need to code a function which returns the subcategories of a category, recursively until there a no sub category:

The first result of query above is:

<page pageid="2545" ns="14" title="Category:Characters" touched="2016-06-02T14:20:11Z" lastrevid="92826" counter="" length="67">
    <categoryinfo size="953" pages="935" files="2" subcats="16" />
</page>

So subcats>0 ? ok, so lets ask for Characters sub categories:

http://gameofthrones.wikia.com/api.php?action=query&generator=categorymembers&gcmtitle=Category:Characters&gcmtype=subcat&gcmlimit=500&prop=categoryinfo|info

etc.

Upvotes: 2

Related Questions