Skip to main content
2 of 2
deleted 6 characters in body; edited tags
Brock Adams
  • 13k
  • 5
  • 39
  • 64

How do I get the total number of records for a given search?

I want to use the Stack Exchange API and get the total number of results returned from the search route.

I wrote this recursive script to find the last page with the has_more=False, is there a better way to do so?

If not, can this be a feature?

My Code:

import requests
api_url = "https://api.stackexchange.com/2.2/"

def recursive_total(site, q, pagesize=100, pagemin=0, pagemax=1000000):
    pageindex = (pagemin + pagemax) / 2
    page = requests.get(api_url + '/search',
                        {'site': site, 'intitle': q, 'page': pageindex + 1, 'pagesize': pagesize}).json()
    if page['has_more']:
        return recursive_total(site, q, pagesize, (pagemin + pagemax) / 2, pagemax)
    else:
        if len(page['items']) == 0:
            return recursive_total(site, q, pagesize, pagemin, (pagemax + pagemin) / 2)
        else:
            return pagesize * pageindex + len(page['items'])