Extracting YouTube Embed Links from a Playlist with Python
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
- Enable YouTube Data API and get credentials
- Write a Python script to fetch playlist items
- Generate embed codes for each video
Step 1: Set Up YouTube API Access
- Go to Google Cloud Console
- Create a new project (or use existing)
- Enable the YouTube Data API v3
- Create an API key under Credentials
- 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.