Back to all posts

How to Download YouTube Videos with an API - The Easy Way (2026 Guide)

Jonathan Geiger
YouTube APIVideo DownloadMP4MP3Developer ToolsTutorial

Need to download YouTube videos programmatically? Whether you're building a content archival system, a media processing pipeline, or a video repurposing tool, downloading YouTube videos via API is the cleanest approach.

In this guide, we'll show you the easiest way to download YouTube videos using the YouTube Video Download API - no yt-dlp servers to manage, no FFmpeg infrastructure, and no broken scrapers.

What Can You Do?

The YouTube Video Download API lets you:

  • Download Videos - MP4, AVI, WebM formats with quality selection (240p to 1080p)
  • Extract Audio - MP3, M4A, OGG, WAV formats from any YouTube video
  • Get Metadata - Video title, duration, thumbnail alongside the download
  • Pre-signed URLs - Get a temporary download link hosted on our servers, no storage needed on your end

The Easy Way: YouTube Video Download API

The simplest and most reliable method is using the YouTube Video Download API. Here's why:

No Infrastructure Needed - No yt-dlp binary, no FFmpeg, no S3 buckets to manage ✅ Multiple Formats - MP4, MP3, AVI, WebM, M4A, OGG, WAV out of the box ✅ Quality Selection - Choose from 240p to 1080p for video formats ✅ Fast & Reliable - Downloads processed on our servers, you just get a link ✅ Format Conversion Built-in - Convert to MP3, AVI, OGG, etc. without FFmpeg

API Endpoint

POST https://api.socialkit.dev/youtube/download

Parameters

ParameterTypeRequiredDescription
urlstringYesYouTube video URL
access_keystringYesYour API access key
formatstringNoOutput format: mp4, mp3, avi, webm, m4a, ogg, wav (default: mp4)
qualitystringNoVideo quality: 240p, 360p, 480p, 720p, 1080p (default: 360p)

Example Request

POST https://api.socialkit.dev/youtube/download
Content-Type: application/json

{
  "access_key": "your-access-key",
  "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
  "format": "mp4",
  "quality": "360p"
}

Example Response

{
  "success": true,
  "data": {
    "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "title": "Rick Astley - Never Gonna Give You Up (Official Music Video)",
    "duration": "3:33",
    "durationSeconds": 213,
    "thumbnail": "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
    "downloadUrl": "https://socialkit-downloads.s3.amazonaws.com/downloads/dQw4w9WgXcQ_1710072000000.mp4?...",
    "fileSize": 4200000,
    "fileSizeMB": "4.00 MB",
    "format": "mp4",
    "quality": "360p",
    "expiresIn": "1 hour"
  }
}

The downloadUrl is a pre-signed S3 link valid for 1 hour. You can use it directly to download the file or redirect your users to it.

Code Examples

JavaScript / Node.js

const axios = require('axios');

async function downloadYouTubeVideo(videoUrl, accessKey, format = 'mp4', quality = '360p') {
  try {
    const response = await axios.post('https://api.socialkit.dev/youtube/download', {
      access_key: accessKey,
      url: videoUrl,
      format,
      quality
    });

    return response.data;
  } catch (error) {
    console.error('Error downloading YouTube video:', error.response?.data || error.message);
    throw error;
  }
}

// Usage
const videoUrl = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
const accessKey = 'your-access-key';

downloadYouTubeVideo(videoUrl, accessKey, 'mp4', '720p')
  .then(data => {
    console.log('Title:', data.data.title);
    console.log('Size:', data.data.fileSizeMB);
    console.log('Download URL:', data.data.downloadUrl);
  });

Python

import requests

def download_youtube_video(video_url, access_key, format='mp4', quality='360p'):
    endpoint = 'https://api.socialkit.dev/youtube/download'

    payload = {
        'access_key': access_key,
        'url': video_url,
        'format': format,
        'quality': quality
    }

    response = requests.post(endpoint, json=payload)
    response.raise_for_status()

    return response.json()

# Usage
video_url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
access_key = 'your-access-key'

data = download_youtube_video(video_url, access_key, format='mp4', quality='720p')

print(f"Title: {data['data']['title']}")
print(f"Size: {data['data']['fileSizeMB']}")
print(f"Download URL: {data['data']['downloadUrl']}")

Save the File Locally (Python)

import requests

def download_and_save(video_url, access_key, output_path, format='mp4', quality='360p'):
    # Step 1: Get the download URL
    result = download_youtube_video(video_url, access_key, format, quality)
    download_url = result['data']['downloadUrl']
    title = result['data']['title']

    # Step 2: Download the file
    print(f'Downloading "{title}"...')
    file_response = requests.get(download_url)

    with open(output_path, 'wb') as f:
        f.write(file_response.content)

    print(f'Saved to {output_path} ({result["data"]["fileSizeMB"]})')

# Usage
download_and_save(
    'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
    'your-access-key',
    'video.mp4',
    format='mp4',
    quality='720p'
)

PHP

<?php
function downloadYouTubeVideo($videoUrl, $accessKey, $format = 'mp4', $quality = '360p') {
    $endpoint = 'https://api.socialkit.dev/youtube/download';

    $payload = json_encode([
        'access_key' => $accessKey,
        'url' => $videoUrl,
        'format' => $format,
        'quality' => $quality
    ]);

    $ch = curl_init($endpoint);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}

// Usage
$videoUrl = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
$accessKey = 'your-access-key';

$data = downloadYouTubeVideo($videoUrl, $accessKey, 'mp4', '720p');

echo "Title: " . $data['data']['title'] . "\n";
echo "Size: " . $data['data']['fileSizeMB'] . "\n";
echo "Download URL: " . $data['data']['downloadUrl'] . "\n";
?>

cURL

curl -X POST "https://api.socialkit.dev/youtube/download" \
  -H "Content-Type: application/json" \
  -d '{
    "access_key": "your-access-key",
    "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "format": "mp4",
    "quality": "720p"
  }'

Supported Formats

Video Formats

FormatExtensionDescription
MP4.mp4Most compatible video format. Works everywhere.
AVI.aviLegacy format for older systems and players.
WebM.webmOpen format, great for web embedding.

Audio Formats

FormatExtensionDescription
MP3.mp3Most popular audio format. Great for podcasts and music.
M4A.m4aApple's audio format. Higher quality than MP3 at same bitrate.
OGG.oggOpen-source audio format.
WAV.wavUncompressed audio. Highest quality, largest file size.

Quality Options

QualityResolutionBest For
240p426x240Smallest file size, mobile data saving
360p640x360Default, good balance of quality and size
480p854x480Standard definition
720p1280x720HD quality
1080p1920x1080Full HD, largest file size

Common Use Cases

1. Extract Audio from YouTube Videos

Perfect for podcast tools, music apps, or audio analysis:

async function extractAudio(videoUrl, accessKey, audioFormat = 'mp3') {
  const data = await downloadYouTubeVideo(videoUrl, accessKey, audioFormat);

  console.log(`Audio extracted: ${data.data.title}`);
  console.log(`Format: ${data.data.format}`);
  console.log(`Size: ${data.data.fileSizeMB}`);
  console.log(`Download: ${data.data.downloadUrl}`);

  return data.data.downloadUrl;
}

// Extract MP3 audio
extractAudio('https://www.youtube.com/watch?v=VIDEO_ID', 'your-access-key', 'mp3');

2. Batch Download Multiple Videos

Download a list of videos in bulk:

async function batchDownload(videoUrls, accessKey, format = 'mp4', quality = '360p') {
  const results = [];

  for (const url of videoUrls) {
    try {
      const data = await downloadYouTubeVideo(url, accessKey, format, quality);
      results.push({
        url,
        title: data.data.title,
        downloadUrl: data.data.downloadUrl,
        size: data.data.fileSizeMB,
        status: 'success'
      });
      console.log(`Downloaded: ${data.data.title} (${data.data.fileSizeMB})`);
    } catch (error) {
      results.push({ url, status: 'failed', error: error.message });
      console.error(`Failed: ${url} - ${error.message}`);
    }
  }

  return results;
}

// Usage
const videos = [
  'https://www.youtube.com/watch?v=VIDEO_1',
  'https://www.youtube.com/watch?v=VIDEO_2',
  'https://www.youtube.com/watch?v=VIDEO_3'
];

batchDownload(videos, 'your-access-key', 'mp4', '720p');

3. Content Repurposing Pipeline

Combine the Download API with other SocialKit APIs for a full repurposing workflow:

async function repurposeVideo(videoUrl, accessKey) {
  // Step 1: Download the video
  const download = await downloadYouTubeVideo(videoUrl, accessKey, 'mp4', '720p');

  // Step 2: Get the transcript
  const transcriptRes = await axios.get('https://api.socialkit.dev/youtube/transcript', {
    params: { access_key: accessKey, url: videoUrl }
  });

  // Step 3: Get an AI summary
  const summaryRes = await axios.get('https://api.socialkit.dev/youtube/summarize', {
    params: { access_key: accessKey, url: videoUrl }
  });

  return {
    videoFile: download.data.downloadUrl,
    transcript: transcriptRes.data.data,
    summary: summaryRes.data.data,
    metadata: {
      title: download.data.title,
      duration: download.data.duration
    }
  };
}

4. Video to Podcast Converter

Convert YouTube videos to audio files for podcast feeds:

async function videoToPodcast(videoUrl, accessKey) {
  const data = await downloadYouTubeVideo(videoUrl, accessKey, 'mp3');

  return {
    title: data.data.title,
    audioUrl: data.data.downloadUrl,
    duration: data.data.durationSeconds,
    format: 'mp3',
    fileSize: data.data.fileSize
  };
}

// Convert multiple videos to podcast episodes
async function createPodcastFeed(videoUrls, accessKey) {
  const episodes = [];

  for (const url of videoUrls) {
    const episode = await videoToPodcast(url, accessKey);
    episodes.push(episode);
    console.log(`Converted: ${episode.title} (${data.data.fileSizeMB})`);
  }

  return episodes;
}

Advanced Features

Download with Automatic Format Selection

Choose the best format based on your use case:

function getOptimalSettings(useCase) {
  switch (useCase) {
    case 'archive':
      return { format: 'mp4', quality: '1080p' };
    case 'mobile':
      return { format: 'mp4', quality: '360p' };
    case 'audio-only':
      return { format: 'mp3', quality: '360p' };
    case 'web-embed':
      return { format: 'webm', quality: '480p' };
    case 'high-quality-audio':
      return { format: 'wav', quality: '360p' };
    default:
      return { format: 'mp4', quality: '720p' };
  }
}

async function smartDownload(videoUrl, accessKey, useCase) {
  const { format, quality } = getOptimalSettings(useCase);
  return downloadYouTubeVideo(videoUrl, accessKey, format, quality);
}

// Usage
smartDownload('https://www.youtube.com/watch?v=VIDEO_ID', 'your-access-key', 'audio-only');

Download and Upload to Your Own Storage

Pipe the download directly to your own S3 bucket or cloud storage:

const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const axios = require('axios');

async function downloadToS3(videoUrl, accessKey, bucket, s3Key) {
  // Get download URL from SocialKit
  const result = await downloadYouTubeVideo(videoUrl, accessKey, 'mp4', '720p');
  const downloadUrl = result.data.downloadUrl;

  // Download the file
  const fileResponse = await axios.get(downloadUrl, { responseType: 'arraybuffer' });

  // Upload to your S3
  const s3 = new S3Client({ region: 'us-east-1' });
  await s3.send(new PutObjectCommand({
    Bucket: bucket,
    Key: s3Key,
    Body: fileResponse.data,
    ContentType: 'video/mp4'
  }));

  console.log(`Uploaded to s3://${bucket}/${s3Key}`);
}

Export Download Results to CSV

const fs = require('fs');

async function exportDownloadsToCSV(videoUrls, accessKey, filename) {
  const results = await batchDownload(videoUrls, accessKey);

  const csv = [
    ['Title', 'URL', 'Format', 'Size', 'Download URL', 'Status'].join(','),
    ...results.map(r => [
      `"${r.title || ''}"`,
      r.url,
      r.format || 'mp4',
      r.size || '',
      r.downloadUrl || '',
      r.status
    ].join(','))
  ].join('\n');

  fs.writeFileSync(filename, csv);
  console.log(`Exported ${results.length} downloads to ${filename}`);
}

Frequently Asked Questions

What's the maximum file size?

Downloads are limited to 10MB per file. For longer or higher-quality videos, try a lower quality setting (240p or 360p) or use an audio-only format (MP3, M4A) which produces much smaller files.

How long do download URLs last?

Download URLs are valid for 1 hour. After that, you'll need to make a new API request to get a fresh URL.

What YouTube URL formats are supported?

The API accepts various YouTube URL formats:

  • https://www.youtube.com/watch?v=VIDEO_ID
  • https://youtu.be/VIDEO_ID
  • https://www.youtube.com/embed/VIDEO_ID
  • https://www.youtube.com/shorts/VIDEO_ID

Can I download private or age-restricted videos?

No, the API only works with publicly available YouTube videos. Private, unlisted, or age-restricted videos cannot be downloaded.

Which format should I choose?

  • MP4 - Best all-around choice for video. Works on every device and platform.
  • MP3 - Best for audio extraction. Smallest audio file size.
  • M4A - Better audio quality than MP3 at the same bitrate.
  • WebM - Best for web embedding with HTML5 video players.
  • WAV - Best for audio processing and editing (uncompressed).

Are there rate limits?

Yes, rate limits depend on your subscription plan. Implement appropriate delays between requests for batch downloads.

Why Use an API Instead of Self-Hosting yt-dlp?

Running your own yt-dlp server is possible, but comes with real challenges:

Challenges of Self-Hosting:

Binary Updates - yt-dlp breaks regularly when YouTube changes their systems ❌ FFmpeg Required - Format conversion needs FFmpeg installed and configured ❌ Storage Management - You need S3 or similar storage for serving files ❌ Bandwidth Costs - Downloading and re-uploading videos uses significant bandwidth ❌ Server Resources - Video processing is CPU and memory intensive ❌ Maintenance Burden - Monitoring, updating, and fixing breakage is ongoing work

Benefits of the API:

Zero Maintenance - We handle yt-dlp updates and YouTube changes ✅ No Infrastructure - No servers, storage, or FFmpeg to manage ✅ Built-in Conversion - 7 formats supported without any setup ✅ Pre-signed URLs - Files served directly from S3, no bandwidth on your end ✅ Simple Integration - One POST request replaces hundreds of lines of code ✅ Cost Effective - Pay per download, no fixed infrastructure costs

Pricing

Get started with free credits to test the API. Paid plans start at just $13/month for 2,000 requests, with volume discounts available.

Get Started

  1. Sign up for free to get your API access key
  2. Make your first download using the examples above
  3. Build your pipeline with reliable YouTube video downloads

Try the YouTube Video Download API today, or use the free YouTube Video Downloader tool - no sign-up required!


Need help? Contact our support team or check out our documentation for more examples and integration guides.