Calling Other APIs
Call another API from your API with httpx - safely. Our first weather endpoint opened 100 connections for 100 calls, turned 36 upstream errors into "200 OK", and crashed with 500 when the service hung. The fixed one shares one client (3 times faster), sets timeouts, maps errors to 404/502/503/504, and retries only what is safe to retry - retrying timeouts made users wait 6.32 s instead of 2.01 s.
What you will be able to do
- Call another API with httpx.AsyncClient
- Share one client for the whole app with lifespan and a dependency
- Set timeouts, and know what httpx does by default
- Turn upstream answers and failures into the right status codes
- Retry only what is safe, with a limit and a pause
- Return only the fields your own clients need
The idea, in plain English
Many APIs are partly a front for other APIs: weather, payments, maps, an AI model. Your route calls the other service, waits, and passes on a result. In Lesson 7.1 we saw that waiting belongs in async def with await - so we use httpx, an HTTP client with an async version (requests has none).
The other service is outside your control. It can be slow, busy, down, or answer with an error. Each of those must become a clear answer from YOUR API - not a crash, not a hang, and not an error dressed up as 200 OK. And calling it well matters too: opening a new connection for every call is slow.
We cannot make a real weather service fail on purpose, so upstream.py is a small fake one on port 8172 that we can make slow, busy or unreachable. It also counts requests and connections. FastAPI 0.143.0, httpx 0.28.1 (httpcore 1.0.9), uvicorn 0.54.0, Python 3.13.17.
Worked example: Our /weather/{city} calls a weather service that we can make slow, busy or unreachable - a first version and a fixed one, each hit with the same four tests.
1 - A normal day
One shared client keeps one connection open and reuses it.
Our clients call our API; our API calls the weather service. Real results from the fixed version.
Words you will see in this lesson
A few words about calling other services.
UpstreamThe service your API calls - here, the weather service.HTTP clientCode that SENDS requests. httpx and requests are HTTP clients.ConnectionAn open line to another server. Opening one takes time; a client can reuse it for many requests.TimeoutHow long you are willing to wait before giving up.RetrySending the same request again after it failed.BackoffWaiting a little longer before each retry, so a busy service can recover.502 / 503 / 504Bad Gateway, Service Unavailable, Gateway Timeout - "the service behind me failed".An everyday example: a travel agent
- You ask a travel agent for a train ticket. The agent calls the railway office - your API calling an upstream API.
- A good agent keeps one phone line open to the railway office all day, instead of dialling again for every customer - one shared client.
- If the railway office does not answer, the agent does not keep you waiting all day: "They are not answering, please come back later" - a timeout and a 504.
- If the line is busy, the agent tries again once or twice, a little later - a retry with backoff. Not forty times in a row.
- And the agent never says "your ticket is booked" when the office said "no seats" - no errors hidden inside a 200.
Example 1 - the fake weather service
upstream.py plays the other company’s API. We never change it while testing - only its mode:
- GET /weather/{city} answers for hyderabad, chennai and delhi, and 404 for other cities. It also sends fields we do not need (station, raw).
- POST /admin/mode sets a delay (to make it hang) and a fail_rate (to make it answer 503 "Busy" sometimes). It also resets the counters.
- GET /admin/stats tells how many requests and how many TCP connections it saw. Each new connection comes from a new client port, so we count ports.
- random.Random(42) makes the "random" failures the same in every run, so the before and after are fair.
"""A fake weather service on port 8172 - slow or flaky on request, so we can test against it."""
import asyncio
import random
from fastapi import FastAPI, HTTPException, Request
app = FastAPI()
TEMPS = {"hyderabad": 31, "chennai": 33, "delhi": 24}
mode = {"delay": 0.0, "fail_rate": 0.0}
stats = {"requests": 0, "connections": set()}
rng = random.Random(42)
@app.get("/weather/{city}")
async def weather(city: str, request: Request):
stats["requests"] += 1
stats["connections"].add(request.client.port) # a new port = a new TCP connection
await asyncio.sleep(mode["delay"])
if rng.random() < mode["fail_rate"]:
raise HTTPException(status_code=503, detail="Busy, try again")
if city not in TEMPS:
raise HTTPException(status_code=404, detail="Unknown city")
return {"city": city, "temp_c": TEMPS[city], "station": "WX-17", "raw": "x" * 200}
@app.post("/admin/mode") # test controls: set delay and failures, reset counters
def set_mode(delay: float = 0.0, fail_rate: float = 0.0):
global rng
mode.update(delay=delay, fail_rate=fail_rate)
stats.update(requests=0, connections=set())
rng = random.Random(42) # the same "random" failures every run
return mode
@app.get("/admin/stats")
def get_stats():
return {"requests": stats["requests"], "connections": len(stats["connections"])}Example 2 - the first version
weather_v1.py is what most first attempts look like - it works on the first try:
- async with httpx.AsyncClient() opens a client, makes one request, and closes it - for every request to our API.
- No timeout is set, so httpx uses its default.
- r.json() passes on whatever came back, and FastAPI sends it with status 200.
import httpx
from fastapi import FastAPI
UPSTREAM = "http://127.0.0.1:8172"
app = FastAPI()
@app.get("/weather/{city}")
async def get_weather(city: str):
async with httpx.AsyncClient() as client: # a new client for every request
r = await client.get(f"{UPSTREAM}/weather/{city}")
return r.json() # whatever came back - even an errorimport asyncio
import sys
import time
import httpx
API = "http://127.0.0.1:8173"
UP = "http://127.0.0.1:8172"
async def run(label, path, n=1, delay=0.0, fail_rate=0.0, at_once=True):
async with httpx.AsyncClient(timeout=60) as c:
await c.post(f"{UP}/admin/mode", params={"delay": delay, "fail_rate": fail_rate})
start = time.perf_counter()
if at_once:
rs = await asyncio.gather(*[c.get(API + path) for _ in range(n)])
else:
rs = [await c.get(API + path) for _ in range(n)]
secs = time.perf_counter() - start
st = (await c.get(f"{UP}/admin/stats")).json()
codes = {}
for r in rs:
codes[r.status_code] = codes.get(r.status_code, 0) + 1
hidden = sum(1 for r in rs if r.status_code == 200 and "detail" in r.text) # an error inside a 200
sample = rs[0].text[:60]
print(f"{label:<26} {n:>3} req {secs:6.2f} s codes {codes} upstream: {st['requests']} req, "
f"{st['connections']} conn" + (f", {hidden} errors hidden in 200s" if hidden else "") + f" | {sample}")
async def main():
print(sys.argv[1])
await run("normal, one by one", "/weather/hyderabad", n=100, at_once=False)
await run("unknown city", "/weather/mumbai")
await run("upstream hangs 10 s", "/weather/chennai", delay=10)
await run("upstream 30% busy (503)", "/weather/delhi", n=100, fail_rate=0.3, at_once=False)
asyncio.run(main())weather_v1
normal, one by one 100 req 2.39 s codes {200: 100} upstream: 100 req, 100 conn | {"city":"hyderabad","temp_c":31,"station":"WX-17","raw":"xxx
unknown city 1 req 0.02 s codes {200: 1} upstream: 1 req, 1 conn, 1 errors hidden in 200s | {"detail":"Unknown city"}
upstream hangs 10 s 1 req 5.02 s codes {500: 1} upstream: 1 req, 1 conn | Internal Server Error
upstream 30% busy (503) 100 req 2.99 s codes {200: 100} upstream: 100 req, 100 conn, 36 errors hidden in 200s | {"city":"delhi","temp_c":24,"station":"WX-17","raw":"xxxxxxxReading the output: four problems
- normal - it works, but 100 calls opened 100 connections, and took 2.39 s.
- unknown city - our API answered 200 with {"detail":"Unknown city"}. A client that checks the status code thinks it got the weather.
- upstream hangs - after 5.02 s: 500 Internal Server Error. httpx has a 5-second default timeout, raised httpx.ReadTimeout, and nothing caught it. Our server log shows the traceback.
- upstream busy - all 100 answers were "200", but 36 of them were the service’s "Busy, try again" error, passed on as success.
- And every answer leaked "station" and "raw" - fields we never meant to offer.
httpx.ReadTimeoutExample 3 - the fixed version
weather.py fixes each problem:
- lifespan opens ONE AsyncClient when the app starts and closes it when the app stops. Requests get it through the get_client dependency (Lesson 4.2) - easy to replace in tests (Lesson 9.2).
- base_url and timeout are set once, on the client. Timeout(2.0, connect=1.0): 1 s to connect, 2 s for each read.
- fetch_with_retry tries up to 3 times for 502, 503 and 504 and for connection errors, waiting 0.1 s, then 0.2 s. It does NOT retry timeouts - see the trap below.
- get_weather turns every outcome into OUR answer: a timeout is 504, an unreachable service is 503, the service’s 404 stays 404, any other error is 502.
- response_model=Weather sends only city and temp_c.
import asyncio
import os
from contextlib import asynccontextmanager
from typing import Annotated
import httpx
from fastapi import Depends, FastAPI, HTTPException, Request
from pydantic import BaseModel
UPSTREAM = os.environ.get("WEATHER_URL", "http://127.0.0.1:8172") # Lesson 8.2: settings
TIMEOUT = httpx.Timeout(2.0, connect=1.0) # 1 s to connect, 2 s for each read
RETRIES = 3 # attempts in total
RETRY_STATUS = {502, 503, 504} # "try again later" answers
@asynccontextmanager
async def lifespan(app: FastAPI):
async with httpx.AsyncClient(base_url=UPSTREAM, timeout=TIMEOUT) as client:
app.state.weather_client = client # ONE client, shared by every request
yield # closed when the app stops
app = FastAPI(lifespan=lifespan)
def get_client(request: Request) -> httpx.AsyncClient:
return request.app.state.weather_client
Client = Annotated[httpx.AsyncClient, Depends(get_client)]
class Weather(BaseModel): # only what OUR clients need
city: str
temp_c: float
async def fetch_with_retry(client: httpx.AsyncClient, url: str) -> httpx.Response:
for attempt in range(1, RETRIES + 1):
try:
r = await client.get(url)
if r.status_code not in RETRY_STATUS:
return r
except httpx.ConnectError: # could not connect: fails fast, safe to retry
if attempt == RETRIES:
raise
# a timeout is NOT retried: it already took 2 s, and the service is probably overloaded
if attempt < RETRIES:
await asyncio.sleep(0.1 * 2 ** (attempt - 1)) # wait 0.1 s, then 0.2 s
return r
@app.get("/weather/{city}", response_model=Weather)
async def get_weather(city: str, client: Client):
try:
r = await fetch_with_retry(client, f"/weather/{city}")
except httpx.TimeoutException:
raise HTTPException(status_code=504, detail="Weather service is too slow")
except httpx.TransportError:
raise HTTPException(status_code=503, detail="Weather service is unreachable")
if r.status_code == 404:
raise HTTPException(status_code=404, detail="Unknown city")
if r.status_code != 200:
raise HTTPException(status_code=502, detail="Weather service error")
return r.json()weather
normal, one by one 100 req 0.71 s codes {200: 100} upstream: 100 req, 1 conn | {"city":"hyderabad","temp_c":31.0}
unknown city 1 req 0.01 s codes {404: 1} upstream: 1 req, 1 conn | {"detail":"Unknown city"}
upstream hangs 10 s 1 req 2.01 s codes {504: 1} upstream: 1 req, 1 conn | {"detail":"Weather service is too slow"}
upstream 30% busy (503) 100 req 6.64 s codes {200: 96, 502: 4} upstream: 147 req, 1 conn | {"city":"delhi","temp_c":24.0}Reading the output again
- normal - 0.71 s instead of 2.39 s, and 1 connection instead of 100. Opening a connection is the slow part; the shared client opens it once.
- unknown city - a real 404.
- upstream hangs - 504 "Weather service is too slow" after 2.01 s, instead of a 500 after 5.02 s.
- upstream busy - 96 successes and 4 clear 502s, instead of 36 hidden errors. The retries cost something: the service got 147 requests instead of 100, and the 100 calls took 6.64 s because of the pauses.
- And the answers carry only {"city":..., "temp_c":...}.
Which status code for which failure?
Your client does not care which service failed - but the code tells them what to do next:
The service says 404The thing does not exist - pass it on.The service says 5xx (after retries)It failed; try later.Cannot connectIt is down or unreachable.TimeoutIt did not answer in time.Unexpected exceptionNever let it become a 500 with a traceback.Tip: httpx.TimeoutException, httpx.ConnectError and friends all inherit from httpx.TransportError, and that from httpx.HTTPError. Catch the specific ones first when they need different answers.
Trap 1: retrying timeouts
Our first fixed version retried everything, timeouts included (weather_retry_timeouts.py). The hang test told the story:
- Before: 504 after 6.32 s - three attempts of 2 s each, plus the pauses. The service got 3 requests.
- A timeout already took the full wait. Retrying it multiplies the wait for the user - and sends more work to a service that is already too slow to answer.
- After: retry only fast failures - 502, 503, 504 and ConnectError. The hang now ends in 2.01 s, with 1 request.
- Retry only requests that are safe to repeat. GET is; a POST that charges a card is not - unless the other API supports idempotency keys.
except (httpx.TimeoutException, httpx.TransportError): # retries timeouts too
if attempt == RETRIES:
raiseweather_retry_timeouts
normal, one by one 100 req 0.71 s codes {200: 100} upstream: 100 req, 1 conn | {"city":"hyderabad","temp_c":31.0}
unknown city 1 req 0.01 s codes {404: 1} upstream: 1 req, 1 conn | {"detail":"Unknown city"}
upstream hangs 10 s 1 req 6.32 s codes {504: 1} upstream: 3 req, 3 conn | {"detail":"Weather service is too slow"}
upstream 30% busy (503) 100 req 6.98 s codes {200: 96, 502: 4} upstream: 148 req, 1 conn | {"city":"delhi","temp_c":24.0}Trap 2: httpx’s retries= does not retry a 503
httpx has a retry setting: httpx.AsyncHTTPTransport(retries=3). It sounds like the whole job - so we tested it against a service that answers 503 every time:
- The service saw ONE request. The 503 came straight back.
- retries= only repeats a failed CONNECTION (like ConnectError). It never looks at status codes.
- So it is useful for "the service is restarting", but for "busy, try again" you need your own loop - like fetch_with_retry - or a library such as tenacity or stamina.
import asyncio
import httpx
UP = "http://127.0.0.1:8172"
async def main():
transport = httpx.AsyncHTTPTransport(retries=3) # httpx's own retry setting
async with httpx.AsyncClient(transport=transport) as c:
await c.post(f"{UP}/admin/mode", params={"fail_rate": 1.0}) # every request: 503
r = await c.get(f"{UP}/weather/delhi")
stats = (await c.get(f"{UP}/admin/stats")).json()
print("service busy: status", r.status_code, "- requests the service saw:", stats["requests"])
try:
await c.get("http://127.0.0.1:8179/weather/delhi") # nothing listens on 8179
except httpx.ConnectError as e:
print("service down: ConnectError after retries -", e)
asyncio.run(main())service busy: status 503 - requests the service saw: 1
service down: ConnectError after retries - All connection attempts failedWhen the service is down
We pointed weather.py at a port where nothing listens (WEATHER_URL=http://127.0.0.1:8179) and called our API:
- Three quick connection attempts with pauses, then 503 "Weather service is unreachable" in 0.39 s.
- A refused connection fails fast. A service that accepts the connection but never answers is the slow case - that is what the timeout is for.
service down -> 503 {"detail":"Weather service is unreachable"} in 0.39 sWatch out: httpx timeouts are per step - 1 s to connect, then 2 s for EACH read - not a total for the whole call. A service that sends a byte every 1.9 s never times out. If you need a hard limit for the whole call, wrap it: await asyncio.wait_for(client.get(url), timeout=3).
Calling other APIs at a glance
One clientOpened at startup, closed at shutdown.
async with httpx.AsyncClient(base_url=URL, timeout=TIMEOUT) as client:
app.state.weather_client = client
yieldTimeoutsDefault 5 s per step. Set your own.
httpx.Timeout(2.0, connect=1.0)
Call itAlways await.
r = await client.get("/weather/delhi")Check the answerNever pass an error on as 200.
if r.status_code == 404: raise HTTPException(404)
FailuresMap to 503 / 504.
except httpx.ConnectError / httpx.TimeoutException
RetryFast failures only, few times, with a pause.
502, 503, 504, ConnectError - not timeouts
Hard total limitFor the whole call.
await asyncio.wait_for(client.get(url), timeout=3)
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Run both servers, then python check.py weather_v1 while ss -tn | grep 8172 | wc -l runs in a loop in a third terminal. What happens to the count?”
“Set the service delay to 1.5 s with curl -X POST "localhost:8172/admin/mode?delay=1.5" and call /weather/delhi. Then try delay=2.5. Where is the line?”
“Set RETRIES = 5 and run the busy test again. How many 502s now - and how many requests did the service get?”
“Replace httpx with requests.get inside the async route (no await). Run the busy test with 10 calls at once. Remember Lesson 7.1 - what happens to the time?”
What usually goes wrong
100 calls opened 100 connections and took 2.39 s instead of 0.71 s. Share one client.
✗ async with httpx.AsyncClient() as client: # inside the route✓ one client in lifespan, given to routes by a dependency36 "Busy" errors and an "Unknown city" went out as 200 OK. Check r.status_code.
✗ return r.json()✓ if r.status_code != 200: raise HTTPException(...)A hanging service became a 500 with a traceback. Catch TimeoutException and ConnectError.
The user waited 6.32 s instead of 2.01 s. Retry fast failures only.
It retries connections only - the service saw one request.
It blocks the event loop (Lesson 7.1). Use httpx.AsyncClient, or a def route.
station and raw leaked. Use a response_model with only what your clients need.
Best practices
- One AsyncClient per upstream service, opened in lifespan.
- Always set a timeout you chose - never rely on the default.
- Map each upstream failure to 404, 502, 503 or 504 - never a 500.
- Retry only safe requests and fast failures, 2-3 times, with backoff.
- Return your own model, not the other API’s answer.
- Test against a fake service you can make slow, busy and down.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Add GET /weather?cities=hyderabad,delhi,chennai that fetches all cities AT THE SAME TIME with asyncio.gather and returns a list. One unknown city must not fail the whole answer - return {"city": ..., "error": "Unknown city"} for it.
Show hintHide hint
await asyncio.gather(*[fetch_one(c) for c in cities], return_exceptions=True), then turn each HTTPException into an error item.
Add a hard limit of 3 s for the whole retry loop with asyncio.wait_for, and answer 504 when it runs out. Test it with fail_rate=1.0 and RETRIES = 10.
Show hintHide hint
except asyncio.TimeoutError (TimeoutError in Python 3.11+) -> 504.
A tiny cache
Weather does not change every second. Save calls to the service by remembering answers for a short time.
- Keep each city’s answer in a dict with the time it was fetched.
- Answer from the dict if the entry is younger than 60 seconds; otherwise call the service.
- Show with the service’s /admin/stats: 100 calls for delhi cause 1 upstream request.
- Make sure errors (404, 502) are NOT cached.
Key points
- Use httpx.AsyncClient with await - requests blocks async routes.
- One shared client: 1 connection and 0.71 s, instead of 100 and 2.39 s.
- httpx waits 5 s by default, then raises - set a timeout and catch it.
- Check the status code: 36 upstream errors were hidden in 200s.
- Retry 502/503/504 and connect errors - not timeouts (6.32 s vs 2.01 s).
- retries= on the transport only retries connections.
Quick check before you move on
Interview questions
How do you call external APIs from a FastAPI service?
With an async client (httpx.AsyncClient) created once in lifespan and injected as a dependency, explicit connect/read timeouts and an overall deadline, mapping upstream status codes and transport errors to 4xx/502/503/504, bounded retries with exponential backoff and jitter for idempotent requests on 5xx and connection errors only, response models that expose only what clients need, and caching or circuit breaking for heavily used or flaky dependencies.
Why not retry every failure?
Retries multiply latency and load: retrying timeouts makes users wait several timeouts and hammers a struggling service; retrying non-idempotent requests can duplicate side effects such as payments. Retry only fast, transient, safe failures, a few times, with backoff - and give up with a clear error.
What is a circuit breaker?
A guard that counts recent failures to a dependency; after too many it "opens" and fails immediately for a cool-down period instead of calling the service, then lets a few trial requests through. It protects both your API’s latency and the failing service.
Quiz
- 1.
Why is a shared client faster?
- 2.
Why should a retry wait a little before trying again?
- 3.
Why 504 for a timeout but 503 for "cannot connect"?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...