DEV Community

Cover image for How to Use ElevenLabs API
Preecha
Preecha

Posted on

How to Use ElevenLabs API

ElevenLabs turns text into natural speech and supports a wide range of voices, languages, and styles. The API makes it easy to embed voice into apps, automate narration pipelines, or build real-time experiences like voice agents. If you can send an HTTP request, you can generate audio in seconds.

Try Apidog today

What Is ElevenLabs API?

ElevenLabs API provides programmatic access to AI models that generate, transform, and analyze audio. The platform started as a text-to-speech service but has expanded into a full audio AI suite.

ElevenLabs API official website

Core capabilities:

  • Text-to-Speech (TTS): Convert written text into spoken audio with control over voice characteristics, emotion, and pacing
  • Speech-to-Speech (STS): Transform one voice into another while preserving the original intonation and timing
  • Voice Cloning: Create a digital replica of any voice from as little as 60 seconds of clean audio
  • AI Dubbing: Translate and dub audio/video content into different languages while maintaining the speaker's voice characteristics
  • Sound Effects: Generate sound effects from text descriptions
  • Speech-to-Text: Transcribe audio into text with high accuracy

The API works over standard HTTP and WebSocket protocols. You can call it from any language, but official SDKs exist for Python and JavaScript/TypeScript with type safety and streaming support built in.

Getting the ElevenLabs API Key

Before making any API call, you need an API key. Here's how to get one:

Step 1: Create a free account. Even the free plan includes API access with 10,000 characters per month.

Step 2: Log in and navigate to the Profile + API Key section. You can find this by clicking your profile icon in the bottom-left corner, or by going directly to the developer settings.

Image

Step 3: Click Create API Key. Copy the key and store it securely—you won't be able to see the full key again.

Image

Important security notes:

  • Never commit your API key to version control
  • Use environment variables or a secrets manager in production
  • API keys can be scoped to specific workspaces for team environments
  • Rotate keys regularly and revoke compromised keys immediately

Set it as an environment variable for the examples in this guide:

# Linux/macOS
export ELEVENLABS_API_KEY="your_api_key_here"

# Windows (PowerShell)
$env:ELEVENLABS_API_KEY="your_api_key_here"
Enter fullscreen mode Exit fullscreen mode

ElevenLabs API Endpoints Overview

The API is organized around several resource groups. Here are the most commonly used endpoints:

Endpoint Method Description
/v1/text-to-speech/{voice_id} POST Convert text to speech audio
/v1/text-to-speech/{voice_id}/stream POST Stream audio as it's generated
/v1/speech-to-speech/{voice_id} POST Convert speech from one voice to another
/v1/voices GET List all available voices
/v1/voices/{voice_id} GET Get details for a specific voice
/v1/models GET List all available models
/v1/user GET Get user account info and usage
/v1/voice-generation/generate-voice POST Generate a new random voice

Base URL: https://api.elevenlabs.io

Authentication: All requests require the xi-api-key header:

xi-api-key: your_api_key_here
Enter fullscreen mode Exit fullscreen mode

Text-to-Speech with cURL

The fastest way to test the API is with a cURL command. This example uses the Rachel voice (ID: 21m00Tcm4TlvDq8ikWAM), one of the default voices available on all plans:

curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM" \
  -H "xi-api-key: $ELEVENLABS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Welcome to our application. This audio was generated using the ElevenLabs API.",
    "model_id": "eleven_flash_v2_5",
    "voice_settings": {
      "stability": 0.5,
      "similarity_boost": 0.75,
      "style": 0.0,
      "use_speaker_boost": true
    }
  }' \
  --output speech.mp3
Enter fullscreen mode Exit fullscreen mode

If successful, you'll get an speech.mp3 file with the generated audio. Play it with any media player.

Breaking down the request:

  • voice_id (in URL): The ID of the voice to use. Every voice in ElevenLabs has a unique ID.
  • text: The content to convert to speech. The Flash v2.5 model supports up to 40,000 characters per request.
  • model_id: Which AI model to use. eleven_flash_v2_5 offers the best balance of speed and quality.
  • voice_settings: Optional fine-tuning parameters (covered in detail below).

The response returns raw audio data. The default format is MP3, but you can request other formats by adding the output_format query parameter:

# Get PCM audio instead of MP3
curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=pcm_44100" \
  -H "xi-api-key: $ELEVENLABS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Hello world", "model_id": "eleven_flash_v2_5"}' \
  --output speech.pcm
Enter fullscreen mode Exit fullscreen mode

Using the Python SDK

The official Python SDK simplifies integration with type hints, built-in audio playback, and streaming support.

Installation

pip install elevenlabs
Enter fullscreen mode Exit fullscreen mode

To play audio directly through your speakers, you may also need mpv or ffmpeg:

# macOS
brew install mpv

# Ubuntu/Debian
sudo apt install mpv
Enter fullscreen mode Exit fullscreen mode

Basic Text-to-Speech

import os
from elevenlabs.client import ElevenLabs
from elevenlabs import play

client = ElevenLabs(
    api_key=os.getenv("ELEVENLABS_API_KEY")
)

audio = client.text_to_speech.convert(
    text="The ElevenLabs API makes it easy to add realistic voice output to any application.",
    voice_id="JBFqnCBsd6RMkjVDRZzb",  # George voice
    model_id="eleven_multilingual_v2",
    output_format="mp3_44100_128",
)

play(audio)
Enter fullscreen mode Exit fullscreen mode

Save Audio to File

from elevenlabs.client import ElevenLabs

client = ElevenLabs(api_key="your_api_key")

audio = client.text_to_speech.convert(
    text="This audio will be saved to a file.",
    voice_id="21m00Tcm4TlvDq8ikWAM",
    model_id="eleven_flash_v2_5",
)

with open("output.mp3", "wb") as f:
    for chunk in audio:
        f.write(chunk)

print("Audio saved to output.mp3")
Enter fullscreen mode Exit fullscreen mode

List Available Voices

from elevenlabs.client import ElevenLabs

client = ElevenLabs(api_key="your_api_key")

response = client.voices.search()

for voice in response.voices:
    print(f"Name: {voice.name}, ID: {voice.voice_id}, Category: {voice.category}")
Enter fullscreen mode Exit fullscreen mode

This prints all voices available in your account, including premade voices, cloned voices, and community voices you've added.

Async Support

For applications using asyncio, the SDK provides AsyncElevenLabs:

import asyncio
from elevenlabs.client import AsyncElevenLabs

client = AsyncElevenLabs(api_key="your_api_key")

async def generate_speech():
    audio = await client.text_to_speech.convert(
        text="This was generated asynchronously.",
        voice_id="21m00Tcm4TlvDq8ikWAM",
        model_id="eleven_flash_v2_5",
    )

    with open("async_output.mp3", "wb") as f:
        async for chunk in audio:
            f.write(chunk)

    print("Async audio saved.")

asyncio.run(generate_speech())
Enter fullscreen mode Exit fullscreen mode

Using the JavaScript SDK

The official Node.js SDK (@elevenlabs/elevenlabs-js) provides full TypeScript support and works in Node.js environments.

Installation

npm install @elevenlabs/elevenlabs-js
Enter fullscreen mode Exit fullscreen mode

Basic Text-to-Speech

import { ElevenLabsClient, play } from "@elevenlabs/elevenlabs-js";

const elevenlabs = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY,
});

const audio = await elevenlabs.textToSpeech.convert(
  "21m00Tcm4TlvDq8ikWAM",  // Rachel voice ID
  {
    text: "Hello from the ElevenLabs JavaScript SDK!",
    modelId: "eleven_multilingual_v2",
  }
);

await play(audio);
Enter fullscreen mode Exit fullscreen mode

Save to File (Node.js)

import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import { createWriteStream } from "fs";
import { Readable } from "stream";
import { pipeline } from "stream/promises";

const elevenlabs = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY,
});

const audio = await elevenlabs.textToSpeech.convert(
  "21m00Tcm4TlvDq8ikWAM",
  {
    text: "This audio will be written to a file using Node.js streams.",
    modelId: "eleven_flash_v2_5",
  }
);

const readable = Readable.from(audio);
const writeStream = createWriteStream("output.mp3");
await pipeline(readable, writeStream);

console.log("Audio saved to output.mp3");
Enter fullscreen mode Exit fullscreen mode

Error Handling

import { ElevenLabsClient, ElevenLabsError } from "@elevenlabs/elevenlabs-js";

const elevenlabs = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY,
});

try {
  const audio = await elevenlabs.textToSpeech.convert(
    "21m00Tcm4TlvDq8ikWAM",
    {
      text: "Testing error handling.",
      modelId: "eleven_flash_v2_5",
    }
  );
  await play(audio);
} catch (error) {
  if (error instanceof ElevenLabsError) {
    console.error(`API Error: ${error.message}, Status: ${error.statusCode}`);
  } else {
    console.error("Unexpected error:", error);
  }
}
Enter fullscreen mode Exit fullscreen mode

The SDK retries failed requests up to 2 times by default, with a 60-second timeout. Both values are configurable.

Streaming Audio in Real Time

For chatbots, voice assistants, or any application where latency matters, streaming lets you start playing audio before the entire response is generated. This is critical for conversational AI where users expect near-instant responses.

Python Streaming


python
from elevenlabs import stream
Enter fullscreen mode Exit fullscreen mode

Top comments (0)