import requests


def fetch_all_pages(query, params=None, headers=None):
    """
    If the query returns paginated results,
    this function recursively fetchs all the results, concatenate and return.
    """
    r = requests.get(query, params=params, headers=headers)
    if not r.ok:
        raise(Exception("Error in fetch_all_pages", "query : ", query, "r.json() ", r.json()))
    link = r.headers.get('link', None)
    if link is None:
        return r.json()

    if 'rel="next"' not in link:
        return r.json()
    else:
        next_url = None
        for url in link.split(','):
            if 'rel="next"' in url:
                next_url = url.split(';')[0][1:-1]

        return r.json() + fetch_all_pages(next_url, params=params, headers=headers)