Extracting YouTube Embed Links from a Playlist with Python

· 2 min read
python youtube-api automation

What We’re Building

A Python script that takes a YouTube playlist and outputs all video embed codes-saving hours of manual copying.

Prerequisites

  • Python 3 installed
  • A Google Cloud account
  • Basic familiarity with APIs

The Approach

  1. Enable YouTube Data API and get credentials
  2. Write a Python script to fetch playlist items
  3. Generate embed codes for each video

Step 1: Set Up YouTube API Access

  1. Go to Google Cloud Console
  2. Create a new project (or use existing)
  3. Enable the YouTube Data API v3
  4. Create an API key under Credentials
  5. Copy and store your API key securely

Step 2: Write the Script

import requests
import json

playlist_id = "PL-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  # Your playlist ID
api_key = "AIzaSyDxxxxxxxxxxxxxxxxxxxxxxxxxx"       # Your API key

url = f"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId={playlist_id}&key={api_key}"

response = requests.get(url)
data = json.loads(response.text)

with open("video_details.txt", "w") as file:
    for item in data["items"]:
        video_title = item["snippet"]["title"]
        video_id = item["snippet"]["resourceId"]["videoId"]
        embed_code = f'<iframe width="560" height="315" src="https://www.youtube.com/embed/{video_id}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'
        file.write(f"{video_title}\n{embed_code}\n\n")

Step 3: Run and Extend

python3 get_youtube_embed_links.py

Check video_details.txt for your results.

Extensions to consider:

  • Handle playlists with >50 videos (pagination via nextPageToken)
  • Output as JSON or Markdown
  • Include video descriptions or thumbnails

The Result

A text file with every video title and its embed code, ready to paste into your website or CMS.

What I’d Do Differently

Handle pagination from the start. YouTube limits responses to 50 items, so larger playlists need multiple API calls.

This took me about 10 minutes to write after 30 minutes of manual copying. If it helped you, let me know on Twitter/Bluesky.

Available for rescue and re-platforming work

I take over platforms that already exist and are in trouble. Node, TypeScript, React and Laravel, mostly in regulated or high-traffic environments. If something needs rescuing, re-platforming or finishing, my full history is on the CV.

Related Posts

Comments