Skip to content
EN
Get API key

YouTube Download / Python

Download YouTube audio to your S3 bucket

Submit an audio download, track the background job and retrieve the location of the delivered MP3 file.

FlashData · Published

An audio waveform delivered to object storage

Prepare your bucket

You need Python 3, a FlashData API key with available credits, an Amazon S3 bucket and storage credentials that can write to that bucket. Keep those credentials on your server.

bash
# Replace YOUR_API_KEY near the top of the code below.
export YOUTUBE_VIDEO_ID='FUfGcZ092b0'
export MEDIA_BUCKET='your-media-bucket'
export AWS_REGION='us-east-1'
export MEDIA_ACCESS_KEY='your-storage-access-key'
export MEDIA_SECRET_KEY='your-storage-secret-key'

Use your actual bucket region. MEDIA_BUCKET is the bucket name, without an s3:// prefix or a directory path. See the storage settings for S3-compatible destinations.

Submit and track the download

Save the script as delivery.py. It submits an audio download to POST /v1/queries, chooses MP3 output and provides the S3 destination.

python
import json
import gzip
import os
import urllib.error
import urllib.request

API_URL = "https://data.flashdata.dev"
API_KEY = "YOUR_API_KEY"


def api_request(path, payload=None, response_headers=None, base_url=API_URL):
    target = path if path.startswith(("https://", "http://")) else base_url + path
    request = urllib.request.Request(
        target,
        data=json.dumps(payload).encode() if payload is not None else None,
        headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
        method="POST" if payload is not None else "GET",
    )
    with urllib.request.urlopen(request, timeout=60) as response:
        if response_headers is not None:
            response_headers.update(response.headers)
        return json.load(response)


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, request, file_pointer, code, message, headers, new_url):
        return None


def result_request(url):
    request = urllib.request.Request(url, headers={"X-API-Key": API_KEY}, method="GET")
    try:
        with urllib.request.build_opener(NoRedirect).open(request, timeout=60):
            raise RuntimeError("Results endpoint did not redirect to storage")
    except urllib.error.HTTPError as response:
        if response.code != 302 or not response.headers.get("Location"):
            raise
        storage_url = response.headers["Location"]
        response.close()
    storage_request = urllib.request.Request(storage_url, headers={"Accept-Encoding": "gzip"})
    with urllib.request.urlopen(storage_request, timeout=60) as response:
        body = response.read()
        if response.headers.get("Content-Encoding") == "gzip":
            body = gzip.decompress(body)
        return json.loads(body)["results"]

import random
import time


def wait_for_job(submission, timeout_seconds=300):
    job_id = submission["id"]
    status_url = next(link["href"] for link in submission["links"] if link["rel"] == "self")
    deadline = time.monotonic() + timeout_seconds
    delay = 1.0
    while time.monotonic() < deadline:
        headers = {}
        payload = api_request(status_url, response_headers=headers)
        job = payload.get("job", payload)
        if job["status"] == "completed":
            results_url = next(link["href"] for link in job["links"] if link["rel"] == "results")
            return result_request(results_url)
        if job["status"] == "failed":
            raise RuntimeError(f"{job_id}: {job.get('error') or 'Job failed'}")
        hint = headers.get("Retry-After", headers.get("retry-after", "1"))
        delay = max(min(5.0, delay * 1.5), float(hint))
        time.sleep(min(delay * random.uniform(1.0, 1.2), max(0, deadline - time.monotonic())))
    raise TimeoutError(f"Keep this job ID and check again later: {job_id}")

storage = {
    "storage_type": "s3",
    "storage_url": os.environ["MEDIA_BUCKET"],
    "object_prefix": "YYYYMMDD",
    "region": os.environ["AWS_REGION"],
    "access_key": os.environ["MEDIA_ACCESS_KEY"],
    "secret_key": os.environ["MEDIA_SECRET_KEY"],
}

job = api_request("/v1/queries", {
    "source": "youtube_download",
    "video_id": os.environ["YOUTUBE_VIDEO_ID"],
    "params": {
        "download_type": "audio",
        "output_format": "mp3",
        "storage": storage,
    },
})
print("Save this job ID before polling:", job["id"], flush=True)
files = wait_for_job(job)
print(json.dumps(files, indent=2))
bash
python3 delivery.py

The script prints the job ID before polling. Save that ID in your application so a restart or timeout does not lose the link to work already submitted.

Read the job receipt

A download submission returns a receipt, not the media file. This recorded receipt contains the job ID and the links used to track progress and read the eventual result.

json
{
  "id": "job_d265c693-950e-40bf-a13e-a432044d99ba",
  "source": "youtube_download",
  "status": "pending",
  "usage": {
    "credits": 0
  },
  "created_at": "2026-09-16T07:51:13.139Z",
  "links": [
    {
      "rel": "self",
      "href": "https://api.flashdata.dev/v2/jobs/job_d265c693-950e-40bf-a13e-a432044d99ba",
      "method": "GET"
    },
    {
      "rel": "results",
      "href": "https://api.flashdata.dev/v2/jobs/job_d265c693-950e-40bf-a13e-a432044d99ba/results",
      "method": "GET"
    }
  ]
}

Use the same API key to read the status link. If the polling deadline expires, keep the ID and check it later. Do not automatically create a replacement job.

Use the delivered file

Once the file is uploaded, the job becomes completed. The results endpoint redirects to stored JSON; the script follows that redirect without forwarding your API key to storage.

Read file_url, file_size and the output-format fields from the result. For a private bucket, use your storage credentials to read the file or create a signed link for your end user. The file URL itself does not make the object public.

Save the job’s JSON result within its 24-hour retention period. The media object remains subject to your own bucket’s lifecycle settings. Download usage is based on actual downloaded data volume.