To send an SMS from FastAPI, share one httpx.AsyncClient through the app lifespan, POST JSON to your provider with the API key in a header, and hand the call to BackgroundTasks so the response returns first. BackgroundTasks is fine for a quick one-off. Anything that must survive a restart needs a real queue.
We make Ready, so the example uses the Ready REST API and only the request shape we document.
A shared async client
import os, uuid
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, BackgroundTasks
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(
base_url="https://api.tryready.com",
headers={"X-API-Key": os.environ["READY_API_KEY"]},
timeout=15,
)
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan) One client for the process keeps connections pooled. Putting the key in the client's default headers means no handler has to remember it.
The send and the endpoint
async def send_sms(http: httpx.AsyncClient, to: str, text: str, key: str) -> int:
res = await http.post(
"/v1/messages",
json={"to": to, "body": text, "consent_attested": True},
headers={"Idempotency-Key": key},
)
return res.status_code
@app.post("/orders/{order_id}/shipped", status_code=202)
async def shipped(order_id: int, tasks: BackgroundTasks):
key = str(uuid.uuid4())
tasks.add_task(send_sms, app.state.http, "+12125550199", f"Order #{order_id} has shipped.", key)
return {"queued": True} to is E.164. Set consent_attested to true only when the recipient agreed to texts. The endpoint answers 202 straight away, and the text goes out after the response.
Where BackgroundTasks stops being enough
BackgroundTasks runs in the same process as your API. If the process restarts after you answered 202 and before the task ran, the text is gone and nothing records that it was meant to be sent. Retries are also on you. So use this split:
| Situation | Use |
|---|---|
| One-off, loss is acceptable (a nice-to-have receipt) | BackgroundTasks |
| Must be sent, must retry (codes, alerts, billing notices) | A queue: insert a row, send from a worker |
| High volume | A worker pool with a rate limit that matches your registered throughput |
For the second row, store the idempotency key on the row when you create it and reuse it on every attempt. A repeated key means the request isn't sent twice, so a retry after a timeout is safe. Retry on timeouts, 429, 5xx and a 409 idempotency_in_progress (the first attempt is still running, so retry with the same key), park other 4xx responses, and send a 409 QUIET_HOURS_BLOCK again once the window opens. Our queue design post and retries guide go through both.
Receiving replies
Replies come back as webhooks to a route you expose. Read await request.body() for the raw bytes, verify the signature against them, return 200 quickly and process later. The inbound webhook guide covers the pattern, and the docs quickstart lists event names.
FAQ
Is requests fine in a FastAPI handler?
Only in a plain def route, which FastAPI runs in a thread pool. In an async def route a blocking requests call stalls the event loop, so use httpx.AsyncClient.
Can I use Celery or ARQ instead?
Yes, and for anything that must be delivered you probably should. The outbox pattern in our Django and Celery guide works the same way in any framework.
How do I test it without texting people?
Use a test key, which simulates every send with no card, number or charge.
The short version
One lifespan client, a stored idempotency key and a queue for anything you can't afford to lose. The messages API docs list every field.
Cost and registration
A segment on the Standard rate is $0.0075 plus a $0.0045 carrier fee, excluding optional screening. An account can send up to 500 texts a month before it registers for 10DLC, and most approvals take 2 to 7 days. See pricing for the full list.