Last active
October 9, 2023 18:00
-
-
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.
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
# 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