Skip to content

Instantly share code, notes, and snippets.

@lonniev
Last active May 30, 2025 20:48
Show Gist options
  • Save lonniev/47cb7a34c053d83edd0999f91d122d83 to your computer and use it in GitHub Desktop.
Save lonniev/47cb7a34c053d83edd0999f91d122d83 to your computer and use it in GitHub Desktop.
Python itertools tactic to fetch all from a paginated API finding all elements which match an arbitrary predicate
import itertools
from typing import Callable
def findSomeItemsByPredicate(
someApi: SomeApi,
predicate: Callable[[Something],Something] ) -> Union[None, list[Something]:
def getOnePage( pageIndex: int ):
# fetch the requested page of Something items, if any
return findItemsPaged( someApi, pageIndex= pageIndex, pageSize= 20 )
# request page after page of content until no more pages are available - without having to know
# the total number of pages available on the service
return list( filter( predicate, itertools.chain.from_iterable( intertools.takewhile( lambda x: x, map( getOnePage, itertools.count(1) ) ) ) ) )
# call like this (here the predicate is the always true existence check)
findSomeItemsByPredicate( myJiraApi, lambda x: x)
@lonniev
Copy link
Author

lonniev commented May 30, 2025

This streams page after page from the API service, stopping once the method which fetches a page at a time returns an empty set.

As those pages arrive, they are filtered to match the provided predicate expression and gathered into a growing list of predicate-matching Somethings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment