ElevenLabs text to speech API quickstart with eleven_v4
Updated November 6, 2026
The picks
Press play to hear each voice read this guide's sample line.
These picks compare my fifteen voices. I own them, and ElevenLabs may pay me when you use them.
Dexter·First integration test
Plain instructional delivery makes missing words easy to notice. It isn't a showcase voice for a dramatic launch.
Jett·Fast explainer output
Brisk, distinct speech for a short application demo. A cluttered test paragraph will expose every redundant phrase.
Heisenberg·Longer narration test
A low, even read for evaluating paragraph continuity. Tight notification slots need a shorter script.
Call POST /v1/text-to-speech/{voice_id} with your ElevenLabs API key in the xi-api-key header and model_id set to eleven_v4. Save the returned bytes as audio. I’d use Dexter for the first integration test because its instructional delivery makes omissions easy to hear, then choose a voice for the finished product.
The examples below make a real, billable generation request when you run them with a valid key. They are alternatives, so you only need to run one. Voice Library API access requires an eligible paid ElevenLabs account. A voice ID copied from a web page does not grant access to the voice.
What should I prepare before sending a request?
Store ELEVENLABS_API_KEY in your process environment or a local secret manager. Use a server process for production. Browser-delivered JavaScript cannot keep a key private, and a public repository is a poor place for it too.
Open Dexter’s voice page, audition the preview, then add Dexter to My Voices. The ID in these examples belongs to Dexter. My machine-readable voice catalog contains the other exact IDs and share links.
Create speech.json with this content.
{
"text": "Your audio file is ready. Play it once before you connect the next step.",
"model_id": "eleven_v4"
}
The output format is in the request URL. mp3_44100_128 is a convenient first download for listening; your delivery platform may require a different format. Check its specifications before producing the whole batch.
How do I save an MP3 with curl?
This example uses a POSIX shell. In PowerShell, use the Node or Python version below, or adapt the environment-variable syntax and invoke curl.exe explicitly.
curl --fail-with-body \
--request POST \
'https://api.elevenlabs.io/v1/text-to-speech/Smxkoz0xiOoHo5WcSskf?output_format=mp3_44100_128' \
--header "xi-api-key: $ELEVENLABS_API_KEY" \
--header 'Content-Type: application/json' \
--data-binary @speech.json \
--output speech.mp3
Inspect the exit status before treating speech.mp3 as usable audio. A failed request can leave an error body in the output file. Open the file in a player only after the command succeeds; don’t solve an unreadable file by renaming it to WAV.
What does the Python version look like?
Python’s standard library can make the same request without an SDK dependency. Save this as speak.py. It reads the environment variable and writes the file only after a successful response.
import json
import os
import urllib.request
from pathlib import Path
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
key = os.environ["ELEVENLABS_API_KEY"]
voice = "Smxkoz0xiOoHo5WcSskf"
url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice}?output_format=mp3_44100_128"
payload = {
"text": "Your audio file is ready. Play it once before you connect the next step.",
"model_id": "eleven_v4",
}
request = urllib.request.Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={"xi-api-key": key, "Content-Type": "application/json"},
method="POST",
)
opener = urllib.request.build_opener(NoRedirect())
with opener.open(request, timeout=120) as response:
if not response.headers.get_content_type().startswith("audio/"):
raise RuntimeError("Expected audio; no file was saved.")
audio = response.read()
Path("speech.mp3").write_bytes(audio)
Let an unsuccessful request stop the process. Catch and classify errors when you turn this into a service, but keep an error response out of the audio folder. Never include the request headers in a public debug report.
Can Node save the same response?
Use a current Node version with built-in fetch, and save this as speak.mjs. Its request matches the other examples.
import { writeFile } from 'node:fs/promises';
const key = process.env.ELEVENLABS_API_KEY;
if (!key) throw new Error('Set ELEVENLABS_API_KEY locally.');
const voice = 'Smxkoz0xiOoHo5WcSskf';
const url = `https://api.elevenlabs.io/v1/text-to-speech/${voice}?output_format=mp3_44100_128`;
const response = await fetch(url, {
method: 'POST',
headers: { 'xi-api-key': key, 'Content-Type': 'application/json' },
body: JSON.stringify({
text: 'Your audio file is ready. Play it once before you connect the next step.',
model_id: 'eleven_v4'
}),
signal: AbortSignal.timeout(120000),
redirect: 'error'
});
if (!response.ok) {
throw new Error(`Speech request failed with HTTP ${response.status}`);
}
if (!(response.headers.get('content-type') || '').startsWith('audio/')) {
throw new Error('Expected audio; no file was saved.');
}
await writeFile('speech.mp3', Buffer.from(await response.arrayBuffer()));
Check the error details privately in your server logs when a status alone isn’t enough. Keep the key out of those logs. For a finished application, also restrict who can request speech and how much text each request accepts.
If the connection times out after submission, the outcome is unknown. Don’t automatically resend the full request. Check your account’s generation history and usage first so an uncertain response doesn’t become several charged copies of the same take.
What should I check when the first request fails?
Work through three layers. First, confirm authentication without printing the key. A missing environment variable is a local configuration problem. An account or permission error needs attention in the ElevenLabs workspace.
Next, check voice access. Use the exact ID, and confirm that the same account can select that voice. Free Voice Library access in the app and Voice Library access through the API are different questions.
Finally, inspect the request shape and model. The reference documents HTTP 422 for an invalid request. Check the returned explanation, the model available to your account, and the output format. Changing the voice at random makes this harder to diagnose. Change one field, then repeat a short test.
How do I move from a connection test to useful audio?
Save the successful request recipe alongside the script, without the key. Add a versioned output name so a retry cannot overwrite the approved take. Listen to the first and last sentence before you connect publishing.
My catalog offers different tests. Jett has a brisk delivery that exposes filler in a short explainer. Heisenberg gives longer explanations room. Their measured rates are close, about 180 and 175 words per minute in my clips, and neither number replaces timing the actual file. A successful API response is the beginning of audio review.
Sources
Related guides
Other jobs where I use the same voices.