Skip to content

Instantly share code, notes, and snippets.

@naxty
Last active October 9, 2023 18:00
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 naxty/8691cd3ae1540821847d2eb792b34eb8 to your computer and use it in GitHub Desktop.
Save naxty/8691cd3ae1540821847d2eb792b34eb8 to your computer and use it in GitHub Desktop.
This code showcases integration with popular public APIs like JSONPlaceholder and REST Countries, demonstrating efficient data fetching using asynchronous HTTP requests by using the httpx framework in combination with fastapi.
# pip install fastapi uvicorn httpx
import asyncio
import httpx
from fastapi import FastAPI
app = FastAPI()
async def fetch_data(url: str):
async with httpx.AsyncClient() as client:
response = await client.get(url)
return response.json()
@app.get("/multi_api")
async def multiple_api_requests():
todos_url = "https://jsonplaceholder.typicode.com/todos/1"
posts_url = "https://jsonplaceholder.typicode.com/posts/1"
users_url = "https://jsonplaceholder.typicode.com/users/1"
tasks = [fetch_data(todos_url), fetch_data(posts_url), fetch_data(users_url)]
results = await asyncio.gather(*tasks)
return {"todos": results[0], "posts": results[1], "users": results[2]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment