Your task: take a YouTube link or video ID and programmatically fetch a downloadable MP3 URL you can save or stream in your app. By the end of this article, you’ll call a real endpoint that returns a direct audio link and metadata, then write a few lines of code to download the file.
What you can build with this
The Youtube to Audio API on Zyla API Hub lets you transform a YouTube video into an audio download URL. It returns a link to the audio file along with useful metadata like title, duration, and file size. Developers use it to:
- Generate MP3s from public YouTube videos for offline playback in a podcasting or learning app.
- Queue audio extraction jobs as part of a larger media workflow.
- Simplify content ingestion by returning a single URL that can be downloaded or proxied by your service.
This API focuses on two concrete actions: given a video ID, return an audio link and metadata; or, given a full YouTube URL, return a ready-to-download URL. No SDK to wrestle with, just simple HTTP GET calls.
Getting started on Zyla API Hub
Zyla API Hub provides thousands of production-ready APIs through one account, one API key, and a consistent subscription model. You can browse, subscribe, and call APIs without setting up multiple vendor accounts. Explore more at zylalabs.com.
To use this API:
- Open the Start 7-day trial on Youtube to Audio API page on Zyla API Hub.
- Click Subscribe (or Start Free Trial when available) and get your API key.
- Send requests with the header Authorization: Bearer YOUR_API_KEY.
Billing is subscription with quota, not pay-per-call. Check the API page for current access options and pricing. You can also discover more APIs and categories at zylalabs.com.
API overview
The Youtube to Audio API exposes two GET endpoints via Zyla’s API gateway:
- Get Audio (by YouTube video ID): returns a direct audio link and metadata
- Download Audio (by full YouTube URL): returns a download URL
All requests use HTTPS and require the Authorization header with a Bearer API key. The examples below are copy-pasteable.
Endpoint: Get Audio (by video ID)
Use this when you have the YouTube video ID and need the audio link plus metadata like title, duration, and file size.
- Method: GET
- URL: https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio
- Required query parameter: id
Example request:
curl -s -X GET "https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio?id=xFYQQPAOz7Y" \
-H "Authorization: Bearer YOUR_API_KEY"
Example JSON 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’ll actually use:
- link: direct URL to the generated audio file. Use this to stream or save the MP3.
- title: title of the source video, useful for filenames and UI labels.
- duration: floating-point value representing the duration in seconds.
- filesize: size in bytes for the downloadable audio, which helps for progress bars and storage planning.
- status/msg/progress: status indicators; progress is a percentage-like number in this sample.
Python example: fetch audio link and download MP3
This sample calls the Get Audio endpoint, extracts the link field, and downloads the file to disk. Replace YOUR_API_KEY with your key from the marketplace page.
import os
import sys
import requests
API_KEY = os.getenv("ZYLA_API_KEY", "YOUR_API_KEY")
VIDEO_ID = "xFYQQPAOz7Y" # Provided in the example request
try:
# Step 1: Get audio metadata and link
meta_resp = requests.get(
"https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio",
headers={"Authorization": f"Bearer {API_KEY}"},
params={"id": VIDEO_ID},
timeout=30,
)
meta_resp.raise_for_status()
data = meta_resp.json()
if data.get("status") != "ok" or "link" not in data:
print("Audio not ready or failed:", data)
sys.exit(1)
audio_url = data["link"]
title = data.get("title", f"{VIDEO_ID}.mp3")
duration = data.get("duration")
size_bytes = data.get("filesize")
# Choose a filename. If title is present, make a safe filename.
filename = f"{title}.mp3" if not title.endswith(".mp3") else title
safe_filename = filename.replace("/", "_")
print(f"Downloading: {safe_filename}")
print(f"Duration (s): {duration}")
print(f"File size (bytes): {size_bytes}")
print(f"URL: {audio_url}")
# Step 2: Download the MP3
with requests.get(audio_url, stream=True, timeout=60) as r:
r.raise_for_status()
with open(safe_filename, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
print("Saved to:", safe_filename)
except requests.HTTPError as e:
print("HTTP error:", e, file=sys.stderr)
sys.exit(1)
except requests.RequestException as e:
print("Request failed:", e, file=sys.stderr)
sys.exit(1)
Tip: since the response includes filesize, you can pre-allocate progress bars. If filesize is not available, stream and infer progress by counting bytes as you write.
Endpoint: Download Audio (by full YouTube URL)
Use this when you have a full YouTube video URL and only need a download URL. This endpoint returns a downloadUrl field that you can fetch in a second step.
- Method: GET
- URL: https://zylalabs.com/api/381/youtube-to-audio-api/22174/download-audio
- Required query parameter: url
Example request:
Example JSON response:
In a typical flow, call this endpoint to get downloadUrl, then perform a standard HTTP GET on that URL to retrieve the binary audio content. If you need title, duration, or file size, prefer the Get Audio endpoint which surfaces those fields alongside the link.
Which endpoint should you use?
- Use Get Audio when you already have the video ID and want metadata (title, duration, filesize) plus the link in one response.
- Use Download Audio when you have a full YouTube URL and only need a downloadable URL, then fetch the file in a second request.
Implementation details that save time
- Authentication: Always send Authorization: Bearer YOUR_API_KEY. Do not put the key in the query string.
- Timeouts: Calls are standard HTTPS GETs. Set practical timeouts on both the metadata request and the file download request. The file download can take longer; stream with chunked reads.
- Filenames: The Get Audio response includes title, which is convenient for filenames. Sanitize it for your OS.
- Durations and sizes: duration is a float in seconds; filesize is bytes. Use filesize for storage budgeting and progress indicators.
- Caching: If you repeatedly request the same video ID or URL, cache the resulting link and metadata in your system with an expiry policy that fits your workflow.
- Retries: Network requests for the returned file link traverse a different host from the Zyla gateway. If a download fails, retry with backoff.
End-to-end example in JavaScript (Node.js)
This script uses fetch to hit the Get Audio endpoint, then downloads the file using the returned link. Use Node 18+ or add a fetch polyfill.
import fs from "node:fs";
import { pipeline } from "node:stream";
import { promisify } from "node:util";
const streamPipeline = promisify(pipeline);
const API_KEY = process.env.ZYLA_API_KEY || "YOUR_API_KEY";
const VIDEO_ID = "xFYQQPAOz7Y";
async function main() {
// Step 1: Get metadata + link
const metaUrl = new URL("https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio");
metaUrl.searchParams.set("id", VIDEO_ID);
const metaResp = await fetch(metaUrl, {
method: "GET",
headers: { Authorization: `Bearer ${API_KEY}` },
});
if (!metaResp.ok) {
console.error("Metadata request failed:", metaResp.status, await metaResp.text());
process.exit(1);
}
const data = await metaResp.json();
if (data.status !== "ok" || !data.link) {
console.error("Audio not ready or missing link:", data);
process.exit(1);
}
const audioUrl = data.link;
const title = data.title || `${VIDEO_ID}.mp3`;
const filename = title.endsWith(".mp3") ? title : `${title}.mp3`;
console.log("Downloading:", filename);
console.log("Duration (s):", data.duration);
console.log("File size (bytes):", data.filesize);
console.log("URL:", audioUrl);
// Step 2: Download the file
const fileResp = await fetch(audioUrl, { method: "GET" });
if (!fileResp.ok || !fileResp.body) {
console.error("Download failed:", fileResp.status, await fileResp.text());
process.exit(1);
}
await streamPipeline(fileResp.body, fs.createWriteStream(filename));
console.log("Saved to:", filename);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
Real-world patterns
- Batch processing: Given a playlist, resolve each video to its ID, then call Get Audio for each ID. Store title, filesize, and link for your ingestion pipeline.
- Microlibrary for your service: Wrap these two endpoints in a small helper with retry, timeout, and filename sanitation.
- Background jobs: Queue ID-to-audio conversions using your job runner. If data.status or progress indicate asynchronous work in your scenario, poll until progress is 100 before downloading.
- Storage handoff: Instead of serving the external link directly, download and re-upload to your own object storage for consistent hosting and access control.
Calling from AI agents via MCP
If you’re wiring this into an AI developer environment, you can call Zyla APIs through the Model Context Protocol using a single MCP endpoint. Any MCP-compatible client (e.g., Claude Code, Cursor, Windsurf) can invoke marketplace APIs through:
Endpoint for agents: https://mcp.zylalabs.com/mcp?apikey=YOUR_API_KEY
Use your Zyla API key with the apikey query parameter on that MCP endpoint, then have your agent perform the same HTTPS calls shown above through its MCP transport. For general MCP information, see the MCP page.
Troubleshooting checklist
- 401 or 403 errors: Ensure the Authorization header is set to Bearer YOUR_API_KEY and your subscription is active.
- No link in response: For the Get Audio endpoint, check status and progress fields and retry after a short delay if needed.
- Download fails mid-stream: Retry the file request with backoff and consider verifying partial file sizes.
- Unexpected titles or filenames: Sanitize special characters and fall back to the video ID if the title is missing.
Security and operational notes
- Never embed your API key in client-side code. Proxy requests through your backend or use server-side calls.
- Log request IDs and timestamps with your calls to simplify debugging and support.
- Consider content policy and user permissions for any downstream distribution of downloaded audio.
Next steps
Once you verify your first request, wrap these calls in your app’s service layer, add minimal retries, and wire progress events to your UI. Use the title, duration, and filesize fields to label and monitor audio processing.
To try it now, open the marketplace page and get an API key: Start 7-day trial on Youtube to Audio API. You’ll get subscription-based access with a quota. Check the API page for current access options and pricing.
FAQ
What authentication header is required?
Send Authorization: Bearer YOUR_API_KEY on every request to the Zyla endpoint.
Which endpoint returns metadata like title and duration?
Use GET https://zylalabs.com/api/381/youtube-to-audio-api/8884/get-audio with the id parameter.
How do I download the actual audio file?
Call one of the API endpoints to get a link or downloadUrl, then perform a standard HTTP GET on that returned URL to retrieve the binary content.
Can I start with a full YouTube URL instead of an ID?
Yes. Use GET https://zylalabs.com/api/381/youtube-to-audio-api/22174/download-audio with the url parameter.
Is there a free plan?
Access is subscription with quota. The item page offers a 7-day trial when available. Check the API page for current access options and pricing.