Spotify API Integration
Relevant source files
The following files were used as context for generating this wiki page:
The Spotify API Integration serves as a core module for the MoodTune backend, enabling the application to access user music data, including profiles, playlists, and detailed audio features. This integration is essential for performing mood analysis on existing Spotify content and providing a personalized user experience.
The system implements the OAuth 2.0 Authorization Code Flow to securely link user Spotify accounts with their MoodTune profiles. Once connected, the backend manages token persistence, automatic refreshes, and data retrieval from various Spotify Web API endpoints.
Authentication and Authorization Flow
The integration utilizes a secure OAuth 2.0 flow to obtain user permissions. This process involves generating an authorization URL, handling a callback with a temporary code, and exchanging that code for long-lived access and refresh tokens.
OAuth Sequence
The following diagram illustrates the interaction between the User, MoodTune Backend, Spotify Accounts Service, and the Supabase Database during the connection process.
State Management
To protect against Cross-Site Request Forgery (CSRF), the system uses a spotify_oauth_states table. A random state string is generated, stored with a 10-minute Time-To-Live (TTL), and verified upon callback.
Sources: db/spotify_oauth_states.sql:2-7, app/api/v1/spotify.py:25-28
Data Models and Storage
The system maintains user connections in a dedicated Supabase table. This allows the backend to perform operations on behalf of the user even when they are not actively interacting with the Spotify-specific endpoints.
Connection Schema
| Field | Type | Description |
|---|---|---|
id | UUID | Primary key for the connection record |
user_id | UUID | Foreign key to the auth.users table |
spotify_user_id | String | The unique identifier provided by Spotify |
access_token | String | Short-lived token for API requests |
refresh_token | String | Long-lived token used to generate new access tokens |
expires_at | TIMESTAMPTZ | The expiration time of the current access token |
Sources: app/schemas/spotify.py:14-23, app/crud/spotify.py:37-53
Token Lifecycle Management
The spotify_api service implements an automatic token refresh mechanism. Before making any request to Spotify, the get_valid_spotify_token function checks if the current token is expired. If it is, the service uses the stored refresh_token to acquire a new access_token and updates the database.
Sources: app/services/spotify_api.py:16-72, app/services/spotify_auth.py:66-89
API Endpoints and Capabilities
The spotify router exposes several endpoints to manage the connection and retrieve data.
Endpoint Summary
| Endpoint | Method | Description |
|---|---|---|
/authorize | GET | Initiates OAuth flow by returning the Spotify auth URL |
/callback | GET | Processes the Spotify redirect and stores tokens |
/status | GET | Checks if the current user has an active connection |
/profile | GET | Returns the user's Spotify display name, email, and followers |
/playlists | GET | Lists the user's Spotify playlists with pagination support |
/disconnect | POST | Removes the Spotify connection from the database |
Sources: app/api/v1/spotify.py:16-218
Audio Feature Extraction
A critical component for the analysis module is the ability to fetch audio features for multiple tracks. The get_audio_features service allows retrieving metrics like valence, energy, and tempo for up to 100 tracks per request.
Sources: app/services/spotify_api.py:155-177, app/api/v1/analysis.py:96-101
Implementation Details
Configuration and Scopes
The integration requires several environment variables and specific Spotify scopes to function correctly.
# app/services/spotify_auth.py:22-38
def generate_authorize_url(state: str) -> str:
_ensure_spotify_config()
params = {
"client_id": settings.SPOTIFY_CLIENT_ID,
"response_type": "code",
"redirect_uri": settings.SPOTIFY_REDIRECT_URI,
"scope": settings.SPOTIFY_SCOPES,
"state": state,
}
return f"https://accounts.spotify.com/authorize?{urlencode(params)}"
The application typically requests scopes such as user-read-private, user-read-email, and playlist-read-private to access relevant user data.
Sources: app/services/spotify_auth.py:33, README.md:9-11
Error Handling
The integration handles various failure scenarios, including:
- Invalid State: Throws a 400 error during callback if the CSRF state is missing or expired.
- Missing Connection: The
get_valid_spotify_tokenservice raises aValueErrorif a user attempts to access Spotify data without a linked account. - Spotify API Errors: Uses
response.raise_for_status()withinhttpxcalls to propagate errors from Spotify's servers.
Sources: app/api/v1/spotify.py:53-57, app/services/spotify_api.py:44, app/services/spotify_api.py:96
Summary
The Spotify API Integration provides the infrastructure for OAuth-based authentication and secure data retrieval. By automating token management and providing clean service interfaces for playlists and audio features, it enables the higher-level analysis modules to focus on mood classification logic while ensuring a seamless connection to the user's Spotify library.