Created
April 28, 2022 10:57
-
-
Save astrojuanlu/c5a416ab2a4abc9ae170b74177cc29d7 to your computer and use it in GitHub Desktop.
Retrieving all paginated results from a JSONAPI using Python, httpx, and asyncio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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