import requests


def fetch(connection, **kwargs):
    kwargs.setdefault('num_results', 0)
    kwargs.setdefault('num_pages', 1)

    method = getattr(requests, connection.method.lower())
    response = method(connection.uri,
                      params=connection.params)

    results = response.json()
    kwargs['num_pages'] += 1

    for result in results['results']:
        if kwargs['num_results'] < connection.max_results:
            kwargs['num_results'] += 1
            yield result

    connection.params['page'] += 1

    if kwargs['num_results'] < connection.max_results:

        yield from fetch(connection, **kwargs)
