Skip to main content

Overview

The AsyncTrackService provides operations for retrieving detailed track information from Spotify’s catalog, including metadata, audio features, and artist information.
This service is available in both async (AsyncTrackService) and sync (TrackService) variants.

Get Track

Retrieve detailed information about a single track.
async def get(self, id: str, market: str | None = None) -> Track
id
str
required
The Spotify ID for the track.Example: "11dFghVXANMlKmJXsNCbNl"
market
str | None
An ISO 3166-1 alpha-2 country code. If provided, track relinking is applied for regional availability.Example: "US", "GB", "CA"Track relinking ensures the returned track is playable in the specified market. If the original track isn’t available, a relinked version may be returned.

Returns

Track
Track
Complete track object with all metadata and related information.Key fields:
  • name - Track title
  • artists - List of artist objects
  • album - Album object containing the track
  • duration_ms - Track duration in milliseconds
  • explicit - Whether track has explicit content
  • popularity - Track popularity (0-100)
  • track_number - Position on album
  • disc_number - Disc number (for multi-disc albums)
  • is_playable - Whether track is playable in the given market
  • preview_url - URL to 30-second preview (if available)
  • external_urls - External URLs (Spotify web player, etc.)
  • uri - Spotify URI

Example

from spotify_sdk import SpotifyClient

client = SpotifyClient(auth_token="your_token")

# Get track details
track = await client.tracks.get("11dFghVXANMlKmJXsNCbNl")

print(f"Track: {track.name}")
print(f"Artists: {', '.join(a.name for a in track.artists)}")
print(f"Album: {track.album.name}")
print(f"Duration: {track.duration_ms // 1000} seconds")
print(f"Popularity: {track.popularity}/100")
print(f"Explicit: {track.explicit}")

if track.preview_url:
    print(f"Preview: {track.preview_url}")

Get Several Tracks

Retrieve information for multiple tracks in a single request.
async def get_several(
    self,
    ids: list[str],
    market: str | None = None,
) -> list[Track]
ids
list[str]
required
List of Spotify track IDs. Maximum 20 IDs per request.Example: ["11dFghVXANMlKmJXsNCbNl", "1301WleyT98MSxVHPZCA6M"]
market
str | None
An ISO 3166-1 alpha-2 country code for track relinking.

Returns

list[Track]
list[Track]
List of track objects in the same order as the requested IDs.Note: If a track ID is invalid or not found, the corresponding position may contain None or be omitted depending on the API response.

Example

# Get several tracks at once
track_ids = [
    "11dFghVXANMlKmJXsNCbNl",
    "1301WleyT98MSxVHPZCA6M",
    "4iV5W9uYEdYUVa79Axb7Rh",
    "6rqhFgbbKwnb9MLmUQDhG6"
]

tracks = await client.tracks.get_several(track_ids)

for track in tracks:
    artists = ", ".join(a.name for a in track.artists)
    print(f"{track.name} - {artists}")
Use get_several() instead of multiple get() calls to reduce API requests and improve performance when retrieving multiple tracks.

Complete Example

Here’s a comprehensive example demonstrating track operations:
from spotify_sdk import SpotifyClient

async def analyze_playlist_tracks(playlist_id: str):
    """Analyze tracks from a playlist."""
    client = SpotifyClient(auth_token="your_token")
    
    # Get playlist tracks
    playlist = await client.playlists.get(playlist_id)
    
    # Extract track IDs (max 20 per request)
    track_ids = [
        item.track.id 
        for item in playlist.tracks.items[:20]
        if item.track
    ]
    
    # Get detailed track information
    tracks = await client.tracks.get_several(track_ids, market="US")
    
    # Analyze the tracks
    total_duration = sum(t.duration_ms for t in tracks)
    avg_popularity = sum(t.popularity for t in tracks) / len(tracks)
    explicit_count = sum(1 for t in tracks if t.explicit)
    
    print(f"=== Playlist Analysis ===")
    print(f"Tracks analyzed: {len(tracks)}")
    print(f"Total duration: {total_duration // 60000} minutes")
    print(f"Average popularity: {avg_popularity:.1f}/100")
    print(f"Explicit tracks: {explicit_count}/{len(tracks)}")
    
    # Find most popular track
    most_popular = max(tracks, key=lambda t: t.popularity)
    print(f"\nMost popular: {most_popular.name} ({most_popular.popularity}/100)")
    
    # List all tracks
    print("\n=== Track List ===")
    for i, track in enumerate(tracks, 1):
        artists = ", ".join(a.name for a in track.artists)
        duration = f"{track.duration_ms // 60000}:{(track.duration_ms % 60000) // 1000:02d}"
        print(f"{i}. {track.name} - {artists} ({duration})")

# Run the analysis
import asyncio
asyncio.run(analyze_playlist_tracks("37i9dQZF1DXcBWIGoYBM5M"))

Error Handling

try:
    # Attempt to get track with empty ID
    track = await client.tracks.get("")
except ValueError as e:
    print(f"Error: {e}")  # "id cannot be empty"

try:
    # Get multiple tracks with empty list
    tracks = await client.tracks.get_several([])
except ValueError as e:
    print(f"Error: {e}")  # "ids cannot be empty"

try:
    # API error for invalid ID
    track = await client.tracks.get("invalid_id")
except Exception as e:
    # Handle 404 or other API errors
    print(f"API Error: {e}")

Track Relinking

When you provide a market parameter, Spotify may return a relinked track if the original isn’t available in that market:
track = await client.tracks.get(
    "11dFghVXANMlKmJXsNCbNl",
    market="JP"
)

# Check if track was relinked
if track.linked_from:
    print(f"Original track: {track.linked_from.id}")
    print(f"Relinked to: {track.id}")

# Check playability
if track.is_playable:
    print("Track is playable in this market")
else:
    print("Track not available")
The Spotify API enforces a maximum of 20 track IDs per get_several() request. For larger batches, split your requests into groups of 20.
Use the market parameter to ensure tracks are playable in your target region. This is especially important for applications serving users in specific countries.

Build docs developers (and LLMs) love