0
0
FastapiHow-ToBeginner · 4 min read

How to Use httpx with FastAPI for Async HTTP Calls

Use httpx.AsyncClient inside FastAPI endpoints to make asynchronous HTTP requests. Import httpx, create an async client, and await requests within your async FastAPI route functions.
📐

Syntax

To use httpx with FastAPI, import httpx and create an AsyncClient instance. Use await client.get(url) or other HTTP methods inside async route functions to perform requests.

  • httpx.AsyncClient(): Creates an async HTTP client.
  • await client.get(url): Sends a GET request asynchronously.
  • async def: Defines an asynchronous FastAPI route.
python
import httpx
from fastapi import FastAPI

app = FastAPI()

@app.get("/fetch")
async def fetch_data():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://api.example.com/data")
    return response.json()
💻

Example

This example shows a FastAPI app with an endpoint /joke that fetches a random joke from an external API using httpx.AsyncClient. It demonstrates how to make async HTTP calls and return the JSON response.

python
import httpx
from fastapi import FastAPI

app = FastAPI()

@app.get("/joke")
async def get_joke():
    url = "https://official-joke-api.appspot.com/random_joke"
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        response.raise_for_status()  # Raises error if request failed
        joke = response.json()
    return {
        "setup": joke["setup"],
        "punchline": joke["punchline"]
    }
Output
{"setup": "Why did the chicken cross the road?", "punchline": "To get to the other side!"}
⚠️

Common Pitfalls

Common mistakes when using httpx with FastAPI include:

  • Not using async with for the client, which can cause resource leaks.
  • Calling httpx methods without await, leading to coroutine warnings or errors.
  • Using synchronous httpx.Client inside async routes, which blocks the event loop.
  • Not handling exceptions like httpx.RequestError or response.raise_for_status().

Correct usage example:

python
import httpx
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/safe-fetch")
async def safe_fetch():
    url = "https://api.example.com/data"
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(url)
            response.raise_for_status()
            return response.json()
    except httpx.RequestError as exc:
        raise HTTPException(status_code=503, detail=f"Request error: {exc}")
    except httpx.HTTPStatusError as exc:
        raise HTTPException(status_code=exc.response.status_code, detail="Bad response from server")
📊

Quick Reference

Tips for using httpx with FastAPI:

  • Always use AsyncClient in async FastAPI routes.
  • Use async with to manage client lifecycle.
  • Await all HTTP calls to avoid blocking.
  • Handle exceptions to keep your API stable.
  • Close clients properly to free resources.

Key Takeaways

Use httpx.AsyncClient with async FastAPI routes for non-blocking HTTP calls.
Always await HTTP requests and use async context managers to manage clients.
Handle exceptions like RequestError and HTTPStatusError to avoid crashes.
Avoid using synchronous httpx.Client inside async routes to prevent blocking.
Close the client properly using async with to free resources.