FastAPI has rapidly gained popularity among Python developers for its ease of use, performance, and support for modern Python features like async/await. In this blog post, we’ll show you how to use FastAPI along with asyncio and the HTTPX library to make concurrent API calls. This technique can help you aggregate data from multiple APIs or perform parallel processing, all while maintaining a responsive web service.
Prerequisites
Before we start, make sure you have Python 3.7 or higher installed on your machine. You’ll also need to install the following packages:
pip install fastapi uvicorn httpx
Creating the FastAPI application
Let’s begin by creating a simple FastAPI application. First, create a new file named main.py
and import the necessary libraries:
import asyncio
import httpx
from fastapi import FastAPI
app = FastAPI()
Integrating HTTPX
Now, let’s define an asynchronous function fetch_data()
that fetches data from a given URL using the HTTPX library:
async def fetch_data(url: str):
async with httpx.AsyncClient() as client:
response = await client.get(url)
return response.json()
Creating the FastAPI Route for Concurrent API Calls
Next, we’ll create a FastAPI route that makes multiple independent requests to external APIs:
@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]
}
In this route, we create a list of tasks for fetching data from three different APIs. We then use asyncio.gather()
to run these tasks concurrently and store the results in a dictionary.
Executing the FastAPI Application
Finally, we can execute the App with the command uvicorn main:app --reload
. This command starts a development server on http://127.0.0.1:8000
. You can now access the combined API data by sending a GET request to http://127.0.0.1:8000/multi_api
. By using curl
or a similar tool, you can see the results of the API call:
curl -X 'GET' \
'http://localhost:8000/multi_api' \
-H 'accept: application/json'
Conclusion
In this blog post, we demonstrated how to create a FastAPI application that makes multiple concurrent API calls using asyncio and HTTPX. This technique can help you improve the performance of your web services by processing multiple API requests in parallel. With FastAPI’s built-in support for async/await, it’s now easier than ever to write high-performance web applications in Python. You can find the complete source code for this tutorial on GitHub.