Skip to content

Instantly share code, notes, and snippets.

@astrojuanlu
Created April 28, 2022 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astrojuanlu/c5a416ab2a4abc9ae170b74177cc29d7 to your computer and use it in GitHub Desktop.
Save astrojuanlu/c5a416ab2a4abc9ae170b74177cc29d7 to your computer and use it in GitHub Desktop.
Retrieving all paginated results from a JSONAPI using Python, httpx, and asyncio
import asyncio
import os
import httpx
async def get_all(url, headers):
result = {}
next_url = url
async with httpx.AsyncClient() as client:
while True:
resp = await client.get(next_url, headers=headers)
for key in "data", "errors", "included":
if key in (content := resp.json()):
result.setdefault(key, []).extend(content[key])
if not (next_url := content.get("links", {}).get("next")):
break
return result
if __name__ == "__main__":
asyncio.run(
get_all(
"https://your_api.com/v1/resource",
{"Authorization": f"Bearer {os.environ['API_TOKEN']}"},
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment