adriangrantdotorg

spotify-web-api

0
0
# Install this skill:
npx skills add adriangrantdotorg/spotify-web-api-skill

Or install specific skill: npx add-skill https://github.com/adriangrantdotorg/spotify-web-api-skill/tree/main/skill/spotify-web-api

# Description

Best practices and workflows for the Spotify Web API. Use when building apps that interact with Spotify to: (1) Handle rate limits and 429 errors, (2) Implement efficient polling strategies, (3) Optimize data fetching, or (4) Manage authentication. Includes specific patterns for 'Smart Polling' and 'Retry-After' handling.

# SKILL.md


name: spotify-web-api
description: "Best practices and workflows for the Spotify Web API. Use when building apps that interact with Spotify to: (1) Handle rate limits and 429 errors, (2) Implement efficient polling strategies, (3) Optimize data fetching, or (4) Manage authentication. Includes specific patterns for 'Smart Polling' and 'Retry-After' handling."


Spotify Web API Skill

This skill encodes best practices for building robust, rate-limit-aware applications using the Spotify Web API.

1. Rate Limiting Strategy (Critical)

Spotify uses a dynamic, rolling 30-second window for rate limiting. There is no fixed "requests per hour" limit.

Handling 429 Response

You must handle HTTP 429 (Too Many Requests) errors gracefully.

Server-Side (Python/Spotipy):
1. Do not block: Configure the client to fail fast rather than retrying indefinitely and blocking your server threads.
2. Extract Header: Capture the Retry-After header from the response. This integer tells you exactly how many seconds to wait.
3. Pass to Client: Return this value to your frontend so the UI can inform the user.

# app.py example
sp = spotipy.Spotify(auth_manager=auth, requests_timeout=10, status_retries=0, retries=0)

try:
    sp.current_user_playing_track()
except spotipy.exceptions.SpotifyException as e:
    if e.http_status == 429:
        retry_after = int(e.headers.get('Retry-After', 5)) # Default to 5s if missing
        return jsonify({"error": "Rate limit", "retry_after": retry_after}), 429

Client-Side (JavaScript):
1. Backoff: If you receive a 429, respect the retry_after value.
2. User Feedback: Display a countdown (e.g., "Retrying in X seconds...") so the user knows the app isn't broken.

2. Polling Best Practices

Safe Intervals

  • Active Tab: Poll no faster than every 5-10 seconds.
  • Background: Significantly reduce polling frequency when the user is not actively viewing the page.

'Smart Polling' Pattern (Page Visibility API)

Use the Page Visibility API to dynamically adjust polling rates. This saves your "request budget" for when the user is actually looking at the dashboard.

// script.js example
let pollInterval = 10000; // 10s default

document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
        console.log("Tab hidden, slowing down to 60s");
        pollInterval = 60000;
    } else {
        console.log("Tab visible, restoring to 10s");
        pollInterval = 10000;
    }
});

function poll() {
    // ... fetch logic ...
    setTimeout(poll, pollInterval);
}

3. Data Fetching Optimization

Maximize Page Size

Always request the maximum number of items allowed per call (usually limit=50 or limit=100) to minimize the total number of HTTP requests.

Before (Inefficient):

# Default limit is often 20
results = sp.playlist_items(playlist_id) 

After (Optimized):

# Fetch 100 items at once
results = sp.playlist_items(playlist_id, limit=100) 

4. Authentication

Use spotipy.oauth2.SpotifyOAuth for robust OAuth 2.0 flow handling.

  • Scopes: Be specific. Only request scopes you actually need.
  • Token Caching: Spotipy handles caching automatically (.cache file), but ensure you handle token validation and refreshing logic if building a long-running server.
def get_auth_manager():
    return SpotifyOAuth(
        client_id=os.getenv("SPOTIPY_CLIENT_ID"),
        client_secret=os.getenv("SPOTIPY_CLIENT_SECRET"),
        redirect_uri=os.getenv("SPOTIPY_REDIRECT_URI"),
        scope="user-read-playback-state user-library-read",
        open_browser=False # Important for server environments
    )

5. Web API vs. Web Playback SDK

  • Web API: Use for Dashboards and Controllers. You want to see what is playing on any device or control playback remotely.
  • Web Playback SDK: Use for Music Players. You want the browser tab itself to emit sound and act as a Spotify Connect device. Do not use this just for metadata.

# README.md

🤖🔊 Spotify Web API Agentic Skill

Spotify Web API Agentic Skill Banner

An Agent Skill for the Spotify Web API that teaches AI agents best practices for building robust, rate-limit-aware applications.

License
Claude Code
Gemini CLI
Codex CLI
Cursor
OpenCode
Antigravity
Agent Skills Standard
PRs Welcome

Transform your AI coding assistant into a Spotify integration expert with battle-tested patterns for handling rate limits, smart polling, and efficient data fetching.


✨ Features

This skill equips AI agents with specialized knowledge to:

  • Handle Rate Limits Gracefully - Implement proper 429 error handling with Retry-After header extraction
  • 🔄 Smart Polling Strategies - Dynamic interval adjustment using the Page Visibility API
  • 📊 Optimize Data Fetching - Maximize page sizes and minimize API calls
  • 🔐 Manage OAuth Authentication - Best practices for SpotifyOAuth configuration
  • 🎯 Choose the Right API - Clear guidance on Web API vs Web Playback SDK
  • 🛡️ Build Resilient Apps - Server-side fail-fast patterns to prevent thread blocking

📋 Prerequisites

To use this skill with Spotify integrations, you'll need:

  • Spotify Developer Account - Register here
  • Spotify App Credentials:
  • SPOTIPY_CLIENT_ID - Your app's client ID
  • SPOTIPY_CLIENT_SECRET - Your app's client secret
  • SPOTIPY_REDIRECT_URI - OAuth callback URL

Set these as environment variables or configure them in your development environment.


🚀 Installation & Integration

This skill follows the Agent Skills open standard and is compatible with multiple AI coding platforms.

Quick Reference Table

Platform Type Installation Path Invocation
Claude Code CLI ~/.claude/skills/spotify-web-api/ Use the Spotify Web API skill... or /spotify-web-api
Claude.ai Web Upload via Settings → Skills Automatically invoked when relevant
Google Antigravity IDE .agent/skills/spotify-web-api/ Automatically invoked when relevant
OpenCode IDE ~/.config/opencode/skills/spotify-web-api/ skill({ name: "spotify-web-api" })
Cursor IDE IDE .cursor/skills/spotify-web-api/ Mentioned in chat with @spotify-web-api
OpenAI Codex CLI ~/.codex/skills/spotify-web-api/ Automatically invoked when relevant
Gemini CLI CLI ~/.gemini/skills/spotify-web-api/ Automatically invoked when relevant

Detailed Installation Instructions

# For Claude Code (personal skills)
git clone https://github.com/adriangrantdotorg/spotify-web-api-skill.git ~/.claude/skills/spotify-web-api

# For Google Antigravity (project skills)
git clone https://github.com/adriangrantdotorg/spotify-web-api-skill.git .agent/skills/spotify-web-api

# For OpenCode (global skills)
git clone https://github.com/adriangrantdotorg/spotify-web-api-skill.git ~/.config/opencode/skills/spotify-web-api

# For Cursor (project skills)
git clone https://github.com/adriangrantdotorg/spotify-web-api-skill.git .cursor/skills/spotify-web-api

# For OpenAI Codex (global skills)
git clone https://github.com/adriangrantdotorg/spotify-web-api-skill.git ~/.codex/skills/spotify-web-api

# For Gemini CLI (global skills)
git clone https://github.com/adriangrantdotorg/spotify-web-api-skill.git ~/.gemini/skills/spotify-web-api

Option 2: Manual Installation

  1. Download the latest release
  2. Extract the spotify-web-api folder
  3. Copy to the appropriate skills directory for your platform (see table above)
  4. Ensure skill/spotify-web-api/SKILL.md exists
  5. Restart your AI assistant or reload the workspace

Option 3: Claude.ai Upload

  1. Navigate to SettingsCapabilitiesSkills
  2. Click Upload skill
  3. Select the ZIP file containing the skill folder
  4. Toggle the skill ON

💡 Usage Examples

Once installed, your AI agent will automatically apply these best practices when working with Spotify. Here are some natural language prompts to try:

Creating a New Integration

"Create a Python Flask app that displays my currently playing track with proper rate limit handling"

The agent will:

  • Configure spotipy with fail-fast retry settings
  • Implement 429 error handling with Retry-After extraction
  • Add user-friendly countdown UI for rate limit waits

Building a Dashboard

"Build a dashboard that polls my playback state every 10 seconds"

The agent will:

  • Implement the Page Visibility API pattern
  • Adjust polling from 10s (active) to 60s (hidden tab)
  • Use limit=50 for any list fetches

Optimizing Existing Code

"Review this Spotify integration code and optimize it for rate limits"

The agent will:

  • Audit retry configurations
  • Check for proper error handling
  • Suggest smart polling improvements
  • Verify maximum page sizes are used

🤝 Contributing

We'd love contributions from the community, thanks! Whether you're fixing bugs, adding examples, or improving documentation, your help makes this skill better for everyone 🙌🏾

See CONTRIBUTING.md for detailed guidelines on:

  • Setting up your development environment
  • Coding standards and best practices
  • Submitting pull requests
  • Adding new examples
  • Reporting issues

Quick Start for Contributors:

# Fork and clone the repository
git clone https://github.com/adriangrantdotorg/spotify-web-api-skill.git
cd spotify-web-api-skill

# Create a feature branch
git checkout -b feature/your-feature-name

# Make your changes and test them
# (Install in your local skills directory and test with your AI agent)

# Commit and push
git commit -m "Add: description of your changes"
git push origin feature/your-feature-name

# Open a Pull Request on GitHub

📚 Additional Resources


🐛 Issues & Support

Encountered a problem or have a suggestion?


Built with ❤️ for Music Lovers & the Open Source Community ✌🏾

# Supported AI Coding Agents

This skill is compatible with the SKILL.md standard and works with all major AI coding agents:

Learn more about the SKILL.md standard and how to use these skills with your preferred AI coding agent.