Interview Prep/Python for DevOps/Language essentials & functions

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.

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions