Skip to content
EN
Get API key
Browse documentation

API reference

YouTube Download API

Get an API key

Download YouTube video or audio to your cloud storage. Choose resolution, format and clip duration, then track the asynchronous job through completion.

YouTube Video Download API — Python examples

Build a request

The 11-character ID from the video URL, not the full URL.

Advanced media options

A format selector overrides quality, frame rate and audio-language selection. Output format and clip bounds still apply. Clip end must follow start; either bound can be omitted.

Storage destination

Blank uses the UTC upload date (YYYYMMDD).

Add your storage credentials on your server before running the code. They need permission to upload files.

Provider credentials and storage requirements
Completion webhookWebhook payload, verification and retries

Markdown applies to completed results. Receipts and job status keep their original fields.

POSThttps://data.flashdata.dev/v1/queries
import gzip
import json
import random
import time
import urllib.error
import urllib.request

api_key = "YOUR_API_KEY"
payload = {
    "source": "youtube_download",
    "video_id": "jNQXAC9IVRw",
    "params": {
        "download_type": "audio_video",
        "video_quality": "<=720",
        "audio_language": "default",
        "upload_metadata": False,
        "output_format": "mp4",
        "storage": {
            "storage_type": "s3",
            "storage_url": "your-media-bucket",
            "access_key": "YOUR_ACCESS_KEY",
            "secret_key": "YOUR_SECRET_KEY",
            "region": "us-east-1",
        },
    },
}

def api_get(url):
    request = urllib.request.Request(url, headers={"X-API-Key": api_key})
    with urllib.request.urlopen(request, timeout=60) as response:
        return json.load(response), response.headers

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

def read_result(url):
    request = urllib.request.Request(url, headers={"X-API-Key": api_key})
    try:
        with urllib.request.build_opener(NoRedirect).open(request, timeout=60):
            raise RuntimeError("Expected a result redirect")
    except urllib.error.HTTPError as response:
        if response.code != 302 or not response.headers.get("Location"):
            raise
        storage_url = response.headers["Location"]
        response.close()
    # Never forward the API key to storage.
    with urllib.request.urlopen(urllib.request.Request(storage_url, headers={"Accept-Encoding": "gzip"}), timeout=60) as response:
        content = response.read()
        if response.headers.get("Content-Encoding") == "gzip":
            content = gzip.decompress(content)
        return json.loads(content)

def link(job, relation):
    return next(item["href"] for item in job["links"] if item["rel"] == relation)

request = urllib.request.Request(
    "https://data.flashdata.dev/v1/queries",
    data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
    headers={"Content-Type": "application/json", "X-API-Key": api_key},
    method="POST",
)
with urllib.request.urlopen(request, timeout=120) as response:
    submission = json.load(response)
jobs = submission.get("queries", [submission])
for submitted in jobs:
    print("Job:", submitted["id"])
    deadline = time.monotonic() + 300
    while time.monotonic() < deadline:
        status, headers = api_get(link(submitted, "self"))
        job = status.get("job", status)
        if job["status"] == "completed":
            result = job.get("result") if submitted["source"] == "youtube_download" and job.get("result") is not None else read_result(link(submitted, "results"))
            print(json.dumps(result, ensure_ascii=False, indent=2))
            break
        if job["status"] == "failed":
            raise RuntimeError(f"{submitted['id']}: {job.get('error', 'Job failed')}")
        hint = headers.get("Retry-After", "1")
        delay = max(1, min(5, int(hint))) if hint.isdigit() else 5
        time.sleep(min(delay * random.uniform(1, 1.2), max(0, deadline - time.monotonic())))
    else:
        raise TimeoutError(f"Still running; save this job ID: {submitted['id']}")
Job receipt, then poll for resultsX-API-Key authentication

Parameters

Send source and video_id at the top level. Source options belong in params. Optional fields can be omitted.

Request body

sourcestring / Required
Set to youtube_download.
video_idstring / Required
The 11-character YouTube video ID, such as FUfGcZ092b0. Accepts letters, numbers, underscores and hyphens.
Exactly 11 charactersDefault: Not set
Accepted format^[A-Za-z0-9_-]{11}$
paramsobject / Required
Settings for this request.
callback_urlstring · nullable / Optional
Async and batch only. Public HTTPS completion URL on port 443, up to 2,048 characters. No user credentials or URL fragment. Omit, use null or an empty string for no notification. In a batch, set this on each query, outside params.
Default: Not set

Video & audio

params.download_typestring / Optional
audio_video merges video and audio; video selects video only; audio selects audio only.
1 to 11 charactersValues: audio_video / video / audioDefault: "audio_video"
params.video_qualitystring / Optional
Video resolution selection. Omit for audio-only downloads.
1 to 40 charactersValues: best / worst / <=144 / ==144 / >=144 / <=360 / ==360 / >=360 / <=480 / ==480 / >=480 / <=720 / ==720 / >=720 / <=1080 / ==1080 / >=1080 / <=1440 / ==1440 / >=1440 / <=2160 / ==2160 / >=2160 / <=4320 / ==4320 / >=4320Default: "<=720"
params.fpsstring / Optional
Frame-rate constraint: >=, <= or == followed by a value from 1 to 240. Omit for audio-only downloads.
1 to 6 charactersDefault: Not set
Accepted format^(?:>=|<=|==)(?:[1-9]\d?|1\d\d|2[0-3]\d|240)$
params.audio_languagestring / Optional
Audio track selection. Applies to audio_video and audio.
1 to 8 charactersValues: default / originalDefault: "default"
params.audio_qualitystring / Optional
Audio-only bitrate in kbps, or best. Numeric choices must be sent as strings. Omit for video downloads.
1 to 10 charactersValues: best / 320 / 256 / 192 / 128Default: "best"
params.output_formatstring / Optional
Video: mp4, webm or mkv. Audio: m4a, mp3 or opus.
1 to 10 charactersValues: mp4 / webm / mkv / m4a / mp3 / opusDefault: mp4 (video) / m4a (audio)
params.yt_dlp_formatstring / Optional
Advanced format selector, from 1 to 1,024 characters after trimming whitespace. Control characters are rejected. Overrides video_quality, fps and audio_language, whose values are then ignored; output format and clipping still apply.
1 to 1,024 charactersDefault: Not set
params.upload_metadataboolean / Optional
Upload a metadata JSON file alongside the media file in your storage.
true or falseDefault: false

Clipping

params.start_atstring / Optional
Clip start in H:MM:SS or HH:MM:SS format, from 00:00:00 to 12:00:00. Defaults to 00:00:00 when only end_at is supplied.
1 to 8 charactersDefault: Not set
Accepted format^\d{1,2}:[0-5]\d:[0-5]\d$
params.end_atstring / Optional
Clip end in H:MM:SS or HH:MM:SS format, up to 12:00:00. Must be later than start_at.
1 to 8 charactersDefault: Not set
Accepted format^\d{1,2}:[0-5]\d:[0-5]\d$

Storage destination

params.storageobject / Required
Destination for completed media files. Only the listed storage fields are accepted.
params.storage.storage_typestring / Required
Storage provider: s3, s3_compatible, oss, gcs, azure, cos, bos or tos.
params.storage.storage_urlstring / Required
Non-empty bucket or container name, up to 1,024 characters. Surrounding whitespace is removed. For s3, use a valid AWS bucket name without a URL or folder path; folders belong in object_prefix.
params.storage.object_prefixstring / Optional
Object-key prefix, 1 to 512 characters. Each slash-separated segment accepts ASCII letters, digits, dots, underscores and hyphens; empty segments, . and .. are rejected. No leading slash. Surrounding whitespace and one trailing slash are removed. YYYYMMDD uses the UTC upload date, including in archive/YYYYMMDD.
Default: "YYYYMMDD"
params.storage.access_keystring / Optional
Access key for S3, S3-compatible, OSS, COS, BOS or TOS; paired with secret_key.
params.storage.secret_keystring / Optional
Secret key for S3, S3-compatible, OSS, COS, BOS or TOS.
params.storage.endpoint_urlstring / Optional
Public HTTPS endpoint for S3-compatible storage or OSS. COS, BOS and TOS derive it from region.
params.storage.regionstring / Optional
Required for COS, BOS and TOS; also supply for S3 and S3-compatible downloads. COS bucket names include the APPID.
params.storage.service_accountobject / Optional
GCS service account: project_id, client_email and PEM private_key.
params.storage.account_namestring / Optional
Azure storage account name. Use the container name in storage_url.
params.storage.sas_tokenstring / Optional
Write-enabled Azure container SAS with expiry and signature.

Response

The request builder submits downloads with Async or Batch and requires params.storage. HTTP 200 with status: pending confirms acceptance, not delivery. Batch returns one job receipt per video ID.

Submission usage.credits is 0. Downloads are billed by delivered media volume after successful delivery; optional metadata files do not add to download charges.

Poll job.status until completed, then retrieve the result JSON. Read media details at results[0], including the uploaded object's file_url, file size and checksum.

Read the result

After the job completes, save the JSON from its results link as response.json. Save this as read-response.py and run python read-response.py. It reads file details without downloading media or making another request.

read-response.py
import json
from pathlib import Path

response = json.loads(Path("response.json").read_text(encoding="utf-8-sig"))
if response.get("status") not in ("done", "completed") or not isinstance(response.get("results"), list):
    raise SystemExit("Expected completed result JSON; inspect the response or job status.")
if not response["results"]:
    print("[]")
    raise SystemExit(0)
result = response["results"][0]

output = {name: result.get(name) for name in (
    "file_url", "file_size", "md5", "duration", "output_format"
)}
# Use your storage credentials to access the media at file_url.
print(json.dumps(output, ensure_ascii=False, indent=2))

Status may include media details in job.result. Default JSON workflows use them when available and otherwise follow the rel: results link; do not assume an inline result is always present.

All submission response fields
FieldDescription
idstringDownload job ID.
sourcestringyoutube_download.
statusstringpending when the job is accepted.
created_atstringJob creation time in ISO 8601 format.
usage.creditsnumber0 at submission. Downloads are charged by delivered data volume after completion.
linksarrayFollow the self link for job status and the results link for completed output.
links[].relstringself or results.
links[].hrefstringURL to query with the same API key.
links[].methodstringGET.
Completed media file fields
FieldDescription
results[0].file_urlstringLocation of the media file in your storage.
results[0].file_sizeintegerMedia file size in bytes.
results[0].downloaded_bytesintegerDelivered media bytes used for billing.
results[0].md5stringMD5 checksum of the media file.
results[0].resolutionstring · nullableVideo resolution, or null for audio-only output or unavailable height.
results[0].durationnumber · nullableDuration in seconds when available.
results[0].output_formatstringOutput file format.
results[0].fpsnumber · nullableFrame rate when available.
results[0].video_codecstring · nullableVideo codec when available.
results[0].audio_codecstring · nullableAudio codec when available.
results[0].dynamic_rangestring · nullableVideo dynamic range when available.
results[0].metadataobject · optionalMetadata file_url, file_size and md5 when upload_metadata is true. Metadata bytes are excluded from download charges.

The fields above describe the default JSON response. Format options apply to the delivery record, not the media file. JSON, plain text and Markdown formats.

Async & batch lifecycle

Submission returns a receipt, not results. Async creates one job; batch returns a separate job in queries[] for every accepted query. Track and retrieve each job independently.

Submit to data.flashdata.dev; read job status and results from api.flashdata.dev with the same X-API-Key. The linked API basics examples use Python and cURL.

  1. 1. Save the job IDs

    Submit one download with Async, or put multiple download requests inside a Batch queries array. Each entry needs params.storage. Save every returned job ID.

    Async request and receipt · Batch request body

  2. 2. Check status

    GET https://api.flashdata.dev/v2/jobs/{jobId}

    pending / processing: poll with a delay and respect Retry-After when present. completed: fetch results. failed: inspect job.error.

    Read job.status, not the submission receipt's status.

    Check status · Python and cURL

    Job status API reference
  3. 3. Fetch results

    GET https://api.flashdata.dev/v2/jobs/{jobId}/results

    After completion, authenticate the result read, then fetch the 302 storage URL without your API key. Save the JSON within 24 hours of completion.

    The JSON describes the media delivered to your storage. Access the media file.

    Fetch results · Python and cURL · Response formats

    Result download API reference

Polling and fetching existing results do not consume query credits. A polling timeout does not cancel the job: keep its ID instead of submitting duplicate billable work. Error codes and retry behavior.

Completion webhooks

Subscribe per query

Set callback_url at the top level of an async request, or inside each query in a batch, outside params. No separate webhook-registration request is required.

Use a public HTTPS URL on port 443. FlashData POSTs a notification for each job reaching completed or failed; the event contains links, not the result itself.

Acknowledge and verify

Return 2xx after durably accepting the event. Deduplicate by delivery_id, also sent as X-Delivery-Id. Redirects are not followed.

Failed deliveries retry with exponential backoff, up to 8 attempts total and at most 24 hours after completion. Keep polling as a fallback.

Callbacks are unsigned. Confirm the job ID, source and terminal status through the authenticated status endpoint before processing the notification. The delivery ID is for deduplication, not proof of authenticity.

Example webhook event and fields
Illustrative completion notification
{
  "delivery_id": "completion:job_example0001",
  "id": "job_example0001",
  "source": "youtube_download",
  "status": "completed",
  "links": [
    {
      "rel": "self",
      "href": "https://api.flashdata.dev/v2/jobs/job_example0001",
      "method": "GET"
    },
    {
      "rel": "results",
      "href": "https://api.flashdata.dev/v2/jobs/job_example0001/results",
      "method": "GET"
    }
  ]
}
FieldDescription
delivery_idstringStable delivery identifier. Deduplicate notifications using this value; it is also sent in the X-Delivery-Id header.
idstringJob ID.
sourcestringRequested data source.
statusstringcompleted or failed.
linksarrayStatus and result links. Notifications do not include result content or an API key.
links[].relstringself or results.
links[].hrefstringAbsolute Management API URL; authenticate with your API key.
links[].methodstringGET.

Full webhook contract and URL restrictions

Bulk file processing

Upload one video ID per line and create the Bulk job with source: youtube_download. Shared options apply to every ID in the file.

Put the required storage destination in options.storage and media settings in options. Single-job and Batch downloads use params.storage instead.

Media files are delivered to your cloud storage. The completed Bulk result includes a manifest and result parts describing the downloads. Save the manifest and parts within 24 hours after the entire Bulk job completes.

Bulk processing API · Python and cURL · Batch JSON requests

Build a Bulk workflow for this source · Pause, resume and recover

Bulk video download — Python toolkit

Storage destination

Include params.storage in each download request. Set storage_url to your bucket or container name and supply credentials with write access. Keep storage credentials on your server.

params.storage · S3-compatible destination
{
  "storage_type": "s3_compatible",
  "storage_url": "your-media-bucket",
  "object_prefix": "archive/YYYYMMDD",
  "endpoint_url": "https://your-s3-endpoint.example.com",
  "region": "your-provider-region",
  "access_key": "<storage-access-key>",
  "secret_key": "<storage-secret-key>"
}

object_prefix defaults to YYYYMMDD, replaced with the UTC upload date. Use a fixed directory or a template such as archive/YYYYMMDD.

s3
Supply access_key and secret_key with write access. Set region to your bucket's AWS region.
s3 example
params.storage · s3
{
  "storage_type": "s3",
  "storage_url": "your-media-bucket",
  "access_key": "YOUR_ACCESS_KEY",
  "secret_key": "YOUR_SECRET_KEY",
  "region": "us-east-1"
}
s3_compatible
Supply access_key, secret_key and a public HTTPS endpoint_url. Set region as required by your provider; Cloudflare R2 uses auto.
s3_compatible example
params.storage · s3_compatible
{
  "storage_type": "s3_compatible",
  "storage_url": "your-media-bucket",
  "access_key": "YOUR_ACCESS_KEY",
  "secret_key": "YOUR_SECRET_KEY",
  "endpoint_url": "https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com",
  "region": "auto"
}
azure
Supply account_name and sas_token, a container SAS with write permission (sp includes w), resource sr=c, expiry se, version sv and signature sig. storage_url is the container name. Do not send endpoint_url, access_key or secret_key.
azure example
params.storage · azure
{
  "storage_type": "azure",
  "storage_url": "your-media-container",
  "account_name": "yourstorageaccount",
  "sas_token": "sv=2023-11-03&sr=c&sp=w&se=2099-01-01T00%3A00%3A00Z&sig=YOUR_SAS_SIGNATURE"
}
bos
Supply access_key, secret_key and region: bj, su or hkg. The endpoint is derived from region when omitted. Use a bucket name without dots.
bos example
params.storage · bos
{
  "storage_type": "bos",
  "storage_url": "your-media-bucket",
  "access_key": "YOUR_ACCESS_KEY",
  "secret_key": "YOUR_SECRET_KEY",
  "region": "bj"
}
cos
Supply access_key, secret_key and an ap-* region, such as ap-hongkong. storage_url must include the APPID suffix. Do not send endpoint_url; it is derived from region.
cos example
params.storage · cos
{
  "storage_type": "cos",
  "storage_url": "your-media-bucket-1234567890",
  "access_key": "YOUR_ACCESS_KEY",
  "secret_key": "YOUR_SECRET_KEY",
  "region": "ap-hongkong"
}
gcs
Supply service_account with project_id, client_email (a .gserviceaccount.com address), and the PEM private_key from your service account. The account must have write access to the bucket. Do not send access_key, secret_key, region or endpoint_url.
gcs example
params.storage · gcs
{
  "storage_type": "gcs",
  "storage_url": "your-media-bucket",
  "service_account": {
    "project_id": "your-project-id",
    "client_email": "[email protected]",
    "private_key": "-----BEGIN PRIVATE KEY-----\nYOUR_PRIVATE_KEY\n-----END PRIVATE KEY-----\n"
  }
}
oss
Supply access_key, secret_key and the bucket region's public HTTPS endpoint_url.
oss example
params.storage · oss
{
  "storage_type": "oss",
  "storage_url": "your-media-bucket",
  "access_key": "YOUR_ACCESS_KEY",
  "secret_key": "YOUR_SECRET_KEY",
  "endpoint_url": "https://oss-cn-hongkong.aliyuncs.com"
}
tos
Supply access_key, secret_key and region with a cn-, ap-, eu- or us- prefix. The endpoint is derived from region when omitted. Use a bucket name without dots.
tos example
params.storage · tos
{
  "storage_type": "tos",
  "storage_url": "your-media-bucket",
  "access_key": "YOUR_ACCESS_KEY",
  "secret_key": "YOUR_SECRET_KEY",
  "region": "cn-beijing"
}

The result’s file_url identifies an object in your storage. Private objects require your storage provider’s authorization or a signed URL; the FlashData API key does not grant access to your bucket.

For a complete submission, polling and download workflow, see Download YouTube audio to Amazon S3.

File delivery

The job's rel: results endpoint defaults to a redirect to result JSON, not an MP4 download. FlashData uploads the actual media to the bucket or container you supplied. Media retention follows your bucket's policy; the job's result JSON expires 24 hours after completion.

results[0].file_url identifies the object but is not automatically a public or signed URL. Access private media with your storage SDK, or generate a short-lived signed URL on your own server. Do not send the FlashData API key to your storage provider.

Enable upload_metadata to upload a {video_id}_meta.json companion in the same prefix. Its location and checksum appear under results[0].metadata.

The console's Browser download mode is separate. Public API downloads use your own storage; do not include console-only browser_delivery settings.

Error recovery

For upload failures or storage 403, check the provider, bucket, region, endpoint and object-write permissions. An unreachable or private file_url does not by itself mean the upload failed: check the object through your storage provider.

A removed or unavailable video cannot be recovered by polling. For unavailable formats, inspect Metadata formats, relax quality constraints or remove the advanced selector. Audio-only requests require m4a, mp3 or opus; video requests require mp4, webm or mkv.

If result JSON has expired, first check your bucket for the delivered media. Resubmitting creates a new download and may incur another charge; it does not recover the old result JSON.

For authentication, balance, request-format and rate-limit failures, use the shared error reference. A submission timeout may still have created a job; check existing work before retrying.

Errors and status codes · When to retry · Rate limits

Step-by-step guide: Download one video and verify delivery

Pricing

PlansUsage ratesper GB deliveredSubscriptionsIncluded credits per billing period
Pay as you go$0.10No monthly feeTop up as needed
Micro$0.08$49.00 / month1,000 credits ($50.00 of API usage) included
Starter$0.07$199.00 / month4,000 credits ($200.00 of API usage) included
Pro$0.06$499.00 / month10,000 credits ($500.00 of API usage) included
Scale$0.05$999.00 / month20,000 credits ($1,000.00 of API usage) included
Business$0.04$1,999.00 / month40,000 credits ($2,000.00 of API usage) included

One account plan. Shared Credits across all three products. Usage covered by included credits is not charged again.

Current prices and plan limits