Add a speech endpoint to a FastAPI service

A FastAPI route that validates text, calls the speech API and returns the audio link, with the errors mapped to useful status codes.

This service wraps the API so your front end never sees the key.

main.py

import os
import httpx
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

app = FastAPI()
API = "https://speakvora.com/api/v1"


class Say(BaseModel):
    text: str = Field(min_length=1, max_length=500)
    voice: str = "af_heart"
    lang: str = "en"


@app.post("/api/speak")
async def speak(body: Say):
    async with httpx.AsyncClient(timeout=40) as client:
        r = await client.post(
            f"{API}/speak",
            headers={"x-api-key": os.environ["SPEAKVORA_KEY"]},
            json=body.model_dump(),
        )
    if r.status_code == 429:
        raise HTTPException(429, detail={"error": "rate_limited", "retry_after_seconds": r.json().get("retry_after_seconds", 1)})
    if r.status_code != 200:
        raise HTTPException(r.status_code, detail=r.json().get("error", "speak_failed"))
    return {"url": r.json()["url"]}

Run it

pip install fastapi uvicorn httpx
SPEAKVORA_KEY=your_key uvicorn main:app --reload

Notes: a brand-new sentence can take seconds, so keep the client timeout above 30 seconds or prepare sentences ahead (guide). Do not log request bodies if they could contain personal information.