Prompt
How do I call a text-to-speech API from Python?
Latest observation
Oct 11, 2026
OpenAI APIWeb search: off
To call a text-to-speech (TTS) API from Python, the basic flow is:
- Send your text to the API with an HTTP request
- Receive audio data back, often as raw bytes or a file URL
- Save or play the audio
Here’s a simple example using requests.
Example: POST text and save returned audio
import requests
API_URL = "https://api.example.com/v1/tts"
API_KEY = "your_api_key_here"
text = "Hello, world!"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {
"text": text,
"voice": "en-US",
"format": "mp3"
}
response = requests.post(API_URL, json=payload, headers=headers)
if response.status_code == 200:
with open("output.mp3", "wb") as f:
f.write(response.content)
print("Saved audio to output.mp3")
else:
print(f"Error {response.status_code}: {response.text}")
If the API returns a download URL instead
Some APIs return JSON like:
{
"audio_url": "https://..."
}
Then you’d do:
import requests
data = response.json()
audio_url = data["audio_url"]
audio_response = requests.get(audio_url)
with open("output.mp3", "wb") as f:
f.write(audio_response.content)
Playing the audio in Python
If you want to play the file immediately, you can use a library like playsound:
from playsound import playsound
playsound("output.mp3")
Common notes
- Check the API docs for:
- required fields (
text,voice,language, etc.) - authentication method
- response format
- rate limits
- required fields (
- For long text, the API may require splitting input into chunks.
- If the API streams audio, you may need to handle streamed responses instead of
response.content.
If you want, I can also show:
- a real example with a specific TTS service like OpenAI, Google, Azure, or ElevenLabs
- how to stream audio instead of saving it all at once
- how to build a reusable Python function for TTS