Apple Music & iTunes Bulk Download

 

The safest and most technically reliable way to download the 30-second previews on an Apple Music page in bulk is to use the iTunes / Apple Search API or the Apple Music API to retrieve the preview URLs and then download them.
(Apple’s official APIs return song previews in the previews or previewUrl fields.)

IMPORTANT LEGAL NOTES

These previews generally belong to the rights holders.

Below is a complete Python script that uses the Apple iTunes Lookup API to fetch all songs belonging to a given artist ID, extract their previewUrl fields, and download each one into a folder.

Usage steps:

  1. Make sure Python 3 is installed.
  2. Install the required packages:
    pip install requests tqdm
    

    (The tqdm library provides a download progress bar.)

  3. Save the following script as download_previews.py, then run:
    python download_previews.py
    
#!/usr/bin/env python3
# download_previews.py

import os
import re
import sys
import json
import requests
from pathlib import Path
from tqdm import tqdm

# Ayarlar
ARTIST_ID = "173099930" # Artist ID
COUNTRY = "TR" # (TR, US, vb.)
OUT_DIR = Path("previews_{}".format(ARTIST_ID))
LIMIT = 200 # Maks results

HEADERS = {
"User-Agent": "Mozilla/5.0 (compatible; preview-downloader/1.0)"
}

def sanitize_filename(s):
s = re.sub(r'[\\/:"*?<>|]+', '_', s)
s = re.sub(r'\s+', ' ', s).strip()
return s

def get_songs_for_artist(artist_id):
url = f"https://itunes.apple.com/lookup?id={artist_id}&entity=song&country={COUNTRY}&limit={LIMIT}"
print("Fetching metadata from:", url)
r = requests.get(url, headers=HEADERS, timeout=20)
r.raise_for_status()
data = r.json()
return data.get("results", [])

def download_url_to(path: Path, url: str):
# Stream download with progress bar
try:
r = requests.get(url, stream=True, headers=HEADERS, timeout=30)
r.raise_for_status()
except Exception as e:
print(f" ! İndirilemedi: {url} -> {e}")
return False

total = int(r.headers.get("content-length", 0))
with open(path, "wb") as f, tqdm(total=total if total>0 else None, unit="B", unit_scale=True, desc=path.name) as bar:
for chunk in r.iter_content(chunk_size=8192):
if not chunk:
continue
f.write(chunk)
bar.update(len(chunk))
return True

def main():
OUT_DIR.mkdir(parents=True, exist_ok=True)
results = get_songs_for_artist(ARTIST_ID)

# results[0] genelde artist meta; şarkılar sonraki öğeler
previews = []
for item in results:
# item wrapper örneği: {"wrapperType":"track","kind":"song", "trackName":"...", "previewUrl":"https://...m4a", ...}
preview_url = item.get("previewUrl") or (item.get("previews") and item["previews"][0].get("url"))
if preview_url:
title = item.get("trackName") or item.get("collectionName") or "unknown"
artist = item.get("artistName") or "artist"
track_id = item.get("trackId") or item.get("collectionId") or ""
previews.append((preview_url, artist, title, track_id))

if not previews:
print("Bu artist için preview bulunamadı veya API cevap başka formatta. Artist ID'yi kontrol et.")
sys.exit(1)

print(f"Toplam {len(previews)} preview bulundu. İndiriliyor...")

for url, artist, title, tid in previews:
safe_name = sanitize_filename(f"{artist} - {title}")
ext = os.path.splitext(url.split('?')[0])[-1] or ".m4a"
out_path = OUT_DIR / f"{safe_name}{ext}"
if out_path.exists():
print("Zaten var, atlanıyor:", out_path.name)
continue
success = download_url_to(out_path, url)
if not success:
print("Başarısız:", url)

print("Bitti. Dosyalar:", OUT_DIR.resolve())

if __name__ == "__main__":
main()

 

 

 

How it works (briefly):

It sends a request to the endpoint:

https://itunes.apple.com/lookup?id=<ARTIST_ID>&entity=song&country=TR

The iTunes API returns a JSON object in which each track includes a previewUrl.
(For more information about the Apple Music / iTunes documentation and the MusicKit preview object, see the Apple Developer docs.)

If:

The previewUrl field is missing or the artist ID returns unexpected data, an alternative approach is to query songs using the Search endpoint (by song names) and then extract the previewUrl. The iTunes Search API documentation will be useful for this — see performance-partners.apple.com.


Additional options / enhancements

After downloading, you can automatically add metadata or convert the files to MP3 using pydub + ffmpeg.

Before using, make sure to review Apple’s Terms of Service and any licensing conditions from the copyright holders.
(Downloading previews for personal or evaluative use is generally fine; redistribution or public publishing can cause legal issues.)

 

 

 

 

 

Leave a Comment