What is a generator function and why is it a good fit for paginated APIs?
IntermediateConceptLanguage essentials & functions
Answer
A function containing yield returns a generator: it runs until the next yield, pauses, and resumes on the next iteration. That lets you hide pagination and stream items lazily.
def all_pages(session, url):
while url:
resp = session.get(url, timeout=10)
resp.raise_for_status()
yield from resp.json()
url = resp.links.get("next", {}).get("url") # GitHub Link header
for repo in all_pages(s, "https://api.github.com/orgs/acme/repos?per_page=100"):
...
The caller can stop early (break) and no further pages are fetched.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner