Flowmails + FastAPI
Send transactional mail from a FastAPI route by calling the Flowmails REST API with httpx — and receive inbound mail as a signed webhook with the exact verification code a FastAPI handler needs.
Step 1
Install the HTTP client
pip install fastapi uvicorn httpxStep 2
Send your first message
import os
import httpx
ENDPOINT = "https://sdk.flowmails.net/api/v1/messages"
API_KEY = os.environ["FLOWMAILS_API_KEY"] # fm_…
async def send_welcome(to: str) -> dict:
async with httpx.AsyncClient(timeout=15) as client:
response = await client.post(
ENDPOINT,
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"from": "welcome@yourdomain.com",
"to": [to],
"subject": "Welcome aboard",
"html": "<h1>You are in</h1><p>Your account is ready.</p>",
# One key per logical mail: a retry with the same key
# replays the first answer instead of sending twice.
"idempotencyKey": f"welcome-{to}",
},
)
response.raise_for_status()
return response.json()Step 2
Call it from a route without blocking the loop
The same send, wrapped in a FastAPI route. Keep the client construction inside the handler or share one AsyncClient on the app lifespan — do not create a new client per request in a hot path.
from fastapi import APIRouter, BackgroundTasks, HTTPException
from app.mail import send_welcome
router = APIRouter()
@router.post("/invite/{email}")
async def invite(email: str, background: BackgroundTasks) -> dict:
# Fire-and-forget: the HTTP response should not wait on the
# mail provider, and a transient failure should not fail signup.
background.add_task(send_welcome, email)
return {"queued": True}- A 4xx from the API is a request problem (bad `from`, missing key scope); a 5xx is worth retrying with the same `idempotencyKey`.
- `response.raise_for_status()` gives you one failure path; parse `response.json()` only after it.
Step 3
Receive inbound mail as a signed webhook
Flowmails POSTs a JSON event when mail arrives. Verify the HMAC before you trust the body: the signature is `sha256=` plus the hex digest of `<timestamp>.<raw body>`, keyed by the endpoint secret shown once in the dashboard.
import hashlib
import hmac
import time
from fastapi import APIRouter, HTTPException, Request
router = APIRouter()
ENDPOINT_SECRET = "whsec_…" # shown once when you create the endpoint
TOLERANCE_SECONDS = 300
def verify(raw_body: bytes, timestamp: str, signature: str) -> bool:
signed = f"{timestamp}.".encode() + raw_body
expected = "sha256=" + hmac.new(
ENDPOINT_SECRET.encode(), signed, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)
@router.post("/webhooks/flowmails")
async def flowmails_webhook(request: Request) -> dict:
raw = await request.body() # bytes, BEFORE json parsing
timestamp = request.headers.get("x-flowmails-timestamp", "")
signature = request.headers.get("x-flowmails-signature", "")
if abs(time.time() - int(timestamp or 0)) > TOLERANCE_SECONDS:
raise HTTPException(status_code=401, detail="stale timestamp")
if not verify(raw, timestamp, signature):
raise HTTPException(status_code=401, detail="bad signature")
event = await request.json()
# Dedupe on X-Flowmails-Delivery-Id; retries reuse it.
return {"ok": True}Reading `await request.json()` first consumes the body stream and makes the signature unverifiable. Read `request.body()` and verify before parsing — that order is the whole security property.
- The timestamp is inside the signed material, so a replayed request is rejected by the 300-second window without a second round trip.
- `X-Flowmails-Delivery-Id` is stable across the retries of one delivery — that is your dedupe key.
- Answer 2xx quickly and do the work after; a slow handler burns the retry budget.
Step 4
Retries, idempotency and the failure modes
The API retries nothing on your behalf for outbound sends. Treat a send like any other side effect: one idempotency key per logical message, a bounded retry, and a dead-letter path for the ones that keep failing.
- Retry only on network errors and 5xx; replay with the SAME `idempotencyKey` so a duplicate is impossible.
- A 409 `sending_not_configured` means the domain has no outbound channel yet — that is a dashboard fix, not a retry.
- Never log the API key or the endpoint secret; log the `X-Flowmails-Delivery-Id` and the response status instead.
Prerequisites
What you need first
- A Flowmails API key — dashboard → Settings → API keys (it is bound to one domain).
- That domain connected in the dashboard, so the `from` address is allowed to send.
- `httpx` for the send call; `fastapi` + `uvicorn` if you also want the webhook receiver.
Runtime notes
Things to know on FastAPI
The REST body uses `html` / `text`. The JavaScript SDK's `html` option becomes `content` on the wire internally — when you call the API directly, send `html` and `text`.
Do the send with `httpx.AsyncClient` inside the request path only for low-volume transactional mail; for anything user-facing move it to a background task or a queue so a slow provider cannot hold the response open.
`idempotencyKey` is what makes a retry safe. A retry without one is a second email.
The webhook receiver must read the RAW body bytes before any JSON parsing — the signature covers the bytes, not the parsed object.
Other integrations