You need an API to programmatically turn a YouTube video into an audio file and ship it this week. By the end of this article you’ll have working curl and Python code that returns a direct MP3 download link from a YouTube URL or ID, and you’ll know how to integrate it into your media pipeline using Zyla API Hub.
What this API does (and why it matters for Media integrations)
The Youtube to Audio API converts a YouTube video into an audio file and returns a direct download link plus useful metadata (title, duration, file size). It exposes two straightforward endpoints: one accepts a YouTube video ID; the other accepts a full YouTube URL. This is ideal for:
- Podcast or lecture ingestion: extract MP3 for downstream transcription or summarization.
- Audio clipping workflows: fetch audio to cut segments, normalize, or mix.
- Content management: archive audio versions of video content for internal search or compliance.
- Agentic tools: let an AI agent pull audio when a user drops a YouTube link.
You’ll call the endpoints via HTTPS on Zyla API Hub using a single key you can reuse across the marketplace.
Getting started on Zyla API Hub
Open the API page for the Youtube to Audio API and subscribe. The hub uses a subscription + quota model, not pay-per-call. There’s no Free Plan; the first API typically offers a 7-day trial or 50 requests to get you unblocked. After subscribing you’ll receive an API key. All requests in this article use the Authorization: Bearer YOUR_API_KEY header.
Go here to start: Start 7-day trial on Youtube to Audio API. You can also browse more than 10,000 public APIs on the Zyla API Hub marketplace with one account and one API key.
Endpoints you will use
The API exposes two GET endpoints on Zyla API Hub. Both require the Authorization header. Only the parameters listed below are supported.
1) Get Audio (by YouTube video ID)
- Method: GET
- URL: https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio
- Required parameter: id (string) — the YouTube video ID.
- Description: Provide a YouTube video ID to receive a direct MP3 link and metadata.
curl example (copy-paste):
curl -s -X GET "https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio?id=xFYQQPAOz7Y" \
-H "Authorization: Bearer YOUR_API_KEY"
Official sample response:
{
"msg": "success",
"link": "https://theta.123tokyo.xyz/get.php/d/fa/xFYQQPAOz7Y.mp3?n=Eminem%20-%20Lose%20Yourself&uT=R&uN=QWxlam9aeWxhTGFicw%3D%3D&h=TcO7xrzRPZ9cGbw2wXP93w&s=1784312338&uT=R&uN=QWxlam9aeWxhTGFicw%3D%3D",
"status": "ok",
"duration": 327.49718169275,
"title": "Eminem - Lose Yourself",
"progress": 100,
"pc": 0,
"filesize": 4181397
}
Field notes you will actually use:
- link: Direct URL to the generated MP3; you can stream or download it.
- title: Video title (helpful for filename defaults).
- duration: Length of the audio in seconds (floating point).
- filesize: Size of the audio file in bytes.
- status and msg: Operational status; useful for simple success checks.
2) Download Audio (by full YouTube URL)
- Method: GET
- URL: https://zylalabs.com/api/381/youtube-to-audio-api/22174/download-audio
- Required parameter: url (string) — full YouTube URL.
- Description: Provide a full YouTube URL to retrieve a downloadable audio URL.
curl example (copy-paste):
Official sample response:
Field notes:
- downloadUrl: A URL you can GET to download the audio for the provided YouTube video.
When to use each endpoint
- Have the video ID already (e.g., “xFYQQPAOz7Y”)? Use Get Audio. You’ll get a direct MP3 link plus duration, title, progress, and file size.
- Have a full YouTube URL (e.g., https://www.youtube.com/watch?v=_Yhyp-_hX2s)? Use Download Audio. You’ll get a downloadable URL for that resource.
If you need metadata (duration/title/filesize) alongside the link, prefer Get Audio with the ID. If your inputs are user-pasted URLs, start with Download Audio for minimal preprocessing.
One working Python example
This Python sample demonstrates calling the Get Audio endpoint, validating the response, and downloading the MP3 to disk using the returned link. Replace YOUR_API_KEY with your key from the API page.
import os
import sys
import json
import time
import urllib.parse
import requests
API_KEY = os.getenv("ZYLALABS_API_KEY", "YOUR_API_KEY")
VIDEO_ID = "xFYQQPAOz7Y" # Example ID; replace in production
def get_audio_by_id(video_id: str):
url = "https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio"
params = {"id": video_id}
headers = {"Authorization": f"Bearer {API_KEY}"}
resp = requests.get(url, headers=headers, params=params, timeout=60)
resp.raise_for_status()
return resp.json()
def download_file(file_url: str, out_path: str):
with requests.get(file_url, stream=True, timeout=300) as r:
r.raise_for_status()
with open(out_path, "wb") as f:
for chunk in r.iter_content(chunk_size=1_048_576): # 1MB
if chunk:
f.write(chunk)
def main():
data = get_audio_by_id(VIDEO_ID)
# Basic checks based on documented fields
if data.get("status") != "ok" or data.get("msg") != "success":
print("Conversion not successful:", json.dumps(data, indent=2))
sys.exit(1)
link = data.get("link")
title = data.get("title") or VIDEO_ID
duration = data.get("duration")
size_bytes = data.get("filesize")
if not link:
print("No download link returned:", json.dumps(data, indent=2))
sys.exit(1)
# Create a safe filename
safe_title = "".join(c for c in title if c.isalnum() or c in (" ", "-", "_")).strip()
filename = f"{safe_title or VIDEO_ID}.mp3"
print(f"Downloading: {title} ({duration:.2f}s, {size_bytes} bytes)")
download_file(link, filename)
print(f"Saved to {filename}")
if __name__ == "__main__":
main()
Notes:
- The Authorization header is required for both endpoints.
- Duration is a floating-point number in seconds.
- filesize is bytes; use it for progress bars or disk quota checks.
- Stream large downloads to avoid loading the entire file into RAM.
Practical tips and integration details
- Retry strategy: Network hops to third-party download links can have intermittent failures. Wrap the final file download in a retry with exponential backoff.
- Filename safety: Use the returned title, but sanitize to avoid invalid filesystem characters.
- Caching: If you process the same YouTube resource repeatedly, cache the final MP3 on your side keyed by video ID to save time and quota.
- Metadata persistence: Store duration and filesize with your asset record to power UX elements like estimated download time.
- Background jobs: Run conversions and downloads asynchronously to keep API latencies off your request path.
Common media workflows you can ship this week
- Transcription pipeline: Use Download Audio on a pasted YouTube URL, fetch the MP3, then hand it to your speech-to-text tool.
- Snippet generator: Use Get Audio to pull audio and metadata, then cut 30–60s teasers for social distribution.
- Knowledge ingestion: Regularly convert long-form educational content into MP3s for downstream indexing and semantic search.
- Agent handoff: Let a chatbot accept a YouTube URL, call the API, and return an audio link for the user to download.
Calling this API from an AI agent via MCP
Every Zyla API can be called from AI agents that support the Model Context Protocol (MCP). Point your MCP-compatible client to the MCP endpoint with your key as a query parameter: https://mcp.zylalabs.com/mcp?apikey=YOUR_API_KEY. From there, your agent can issue the same HTTPS calls to the Youtube to Audio API endpoints referenced above. For agent configuration details, see the MCP resource.
Typical flow for agents:
- Accept user input (YouTube URL or ID).
- Choose the corresponding endpoint (Get Audio for IDs; Download Audio for full URLs).
- Return the final MP3 download link back to the user or to the next tool in the chain.
Troubleshooting
- 401 Unauthorized: Ensure the Authorization header is present and the bearer token is your active key from the marketplace.
- Missing or invalid parameter: Each endpoint requires exactly one parameter (id for Get Audio, url for Download Audio). Verify formatting and URL-encoding for query strings.
- Slow downloads: Stream the file and consider a CDN on your side if redistributing assets to many users.
- Quota planning: The marketplace uses subscription + quota. Monitor your usage and choose a plan that covers your weekly conversion volume. Check the API page for current access options and pricing.
Security and compliance reminders
- Respect content rights and terms when converting and storing audio.
- Regenerate download links on demand rather than hardcoding third-party URLs that may expire.
- Store only what you need: cache the audio and minimal metadata (title, duration, filesize) for your use case.
Copy-paste: minimal JavaScript fetch snippet
If you prefer JavaScript, here’s a tiny example targeting Get Audio by ID and logging the direct MP3 link:
const API_KEY = "YOUR_API_KEY";
const videoId = "xFYQQPAOz7Y";
async function getAudioLinkById(id) {
const url = new URL("https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio");
url.searchParams.set("id", id);
const resp = await fetch(url.toString(), {
method: "GET",
headers: { "Authorization": `Bearer ${API_KEY}` }
});
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}`);
}
const data = await resp.json();
if (data.status !== "ok" || data.msg !== "success" || !data.link) {
throw new Error(`Conversion not ready or failed: ${JSON.stringify(data)}`);
}
return {
mp3Url: data.link,
title: data.title,
durationSec: data.duration,
sizeBytes: data.filesize
};
}
getAudioLinkById(videoId)
.then(info => {
console.log("MP3 URL:", info.mp3Url);
console.log("Title:", info.title);
console.log("Duration (s):", info.durationSec);
console.log("Size (bytes):", info.sizeBytes);
})
.catch(err => {
console.error("Error:", err);
});
Shipping checklists
For a batch ingestion job
- Input normalization: Convert any pasted YouTube URL into an ID when you need metadata (Get Audio), or pass the URL as-is (Download Audio).
- Parallelism: Throttle concurrent conversions and downloads to match your compute and network capacity.
- Storage keys: Use the YouTube video ID as the canonical asset key across your system.
- Error handling: On transient failures, retry the final file download; on 4xx errors, log and skip.
For a user-triggered download button
- Server call: Hit the endpoint server-side, not from the browser, to protect your API key.
- Temporary URLs: Fetch a fresh link on click to avoid stale URLs.
- Progress UI: Use filesize to compute progress and duration for “time remaining” estimates.
Recap: exact endpoints to use
- GET https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio?id=YOUR_VIDEO_ID — returns link, title, duration, progress, filesize.
- GET https://zylalabs.com/api/381/youtube-to-audio-api/22174/download-audio?url=YOUR_YOUTUBE_URL — returns downloadUrl for the provided video URL.
Authentication header for both: Authorization: Bearer YOUR_API_KEY.
FAQ
Q: Do I need the full URL or just the video ID?
A: Use Get Audio if you have the video ID and want metadata with the MP3 link. Use Download Audio if you have the full YouTube URL.
Q: What does the filesize represent?
A: It’s the MP3 size in bytes. Use it to estimate bandwidth needs and render progress bars.
Q: Can I call this from an AI agent?
A: Yes. Point your MCP-compatible client to the MCP endpoint (https://mcp.zylalabs.com/mcp?apikey=YOUR_API_KEY) and have the agent call the same API URLs shown above.
Q: How is billing handled?
A: Zyla uses a subscription + quota model, not pay-per-call. There is no Free Plan. The first API typically offers a 7-day trial or 50 requests to get started. Check the API page for current access options and pricing.
Q: What headers do I need?
A: Include Authorization: Bearer YOUR_API_KEY in every request.
Ready to implement your media flow? Get your key and start converting videos to MP3 now: Start 7-day trial on Youtube to Audio API.