0
0
FastAPIframework~5 mins

Async HTTP client calls in FastAPI

Choose your learning style9 modes available
Introduction

Async HTTP client calls let your FastAPI app ask other servers for data without waiting and blocking your app. This keeps your app fast and responsive.

When your FastAPI app needs to get data from another website or API.
When you want to call multiple APIs at the same time to save time.
When you want your app to stay responsive while waiting for slow servers.
When you build microservices that talk to each other over HTTP.
When you want to fetch data from external sources without blocking your main code.
Syntax
FastAPI
import httpx

async with httpx.AsyncClient() as client:
    response = await client.get('https://example.com')
    data = response.json()

Use async with to create an async client that closes properly.

Use await before the HTTP call to wait for the response without blocking.

Examples
Basic async GET request to fetch JSON data.
FastAPI
import httpx

async def fetch_data():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://api.example.com/data')
        return response.json()
Fetch multiple URLs at the same time using asyncio.gather.
FastAPI
import httpx
import asyncio

async def fetch_multiple():
    async with httpx.AsyncClient() as client:
        urls = ['https://api1.com', 'https://api2.com']
        tasks = [client.get(url) for url in urls]
        responses = await asyncio.gather(*tasks)
        return [r.json() for r in responses]
Send data with an async POST request.
FastAPI
import httpx

async def post_data():
    async with httpx.AsyncClient() as client:
        response = await client.post('https://api.example.com/post', json={'key': 'value'})
        return response.status_code
Sample Program

This FastAPI app has one route /fetch. When you visit it, the app makes an async HTTP GET call to a test API and returns the JSON data it gets back.

FastAPI
from fastapi import FastAPI
import httpx
import asyncio

app = FastAPI()

@app.get('/fetch')
async def fetch():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://jsonplaceholder.typicode.com/todos/1')
        data = response.json()
    return data
OutputSuccess
Important Notes

Always use async with to ensure the client closes connections properly.

Use await to pause your function until the HTTP response arrives without freezing your app.

Handle exceptions like timeouts or connection errors to avoid crashes.

Summary

Async HTTP client calls let your FastAPI app talk to other servers without waiting and blocking.

Use httpx.AsyncClient with async with and await for clean, fast calls.

This helps your app stay responsive and handle many requests efficiently.