Search code examples
mediawiki-apiwikimedia-commons

How to search for page/category in Wikimedia Commons by API?


I want to be able to query Wikimedia commons to be able to find a page or category.

Naïvely I thought https://commons.wikimedia.org/w/api.php?action=query&list=search&srsearch=Albert%20Einstein would do, however as you can see it does not return the page I want (Albert Einstein).

Also is there any way to restrict the search to only return categories? For example: Category: Albert Einstein

EDIT: I figured out what I wanted, this will give back categories and pages.

https://commons.wikimedia.org/w/api.php?action=query&generator=search&prop=info&gsrsearch=Albert%20Einstein&gsrnamespace=14|0


Solution

  • By default your query returns only 10 results, so add srlimit=500 in your request and you will see Albert Einstein.

    https://commons.wikimedia.org/w/api.php?action=query&list=search&srsearch=Albert%20Einstein&srlimit=500
    

    To restrict the search to only return categories you need to use srnamespace=14:

    https://commons.wikimedia.org/w/api.php?action=query&list=search&srsearch=Albert%20Einstein&srlimit=500&srnamespace=14