A step-by-step journey of combining FastAPI, OpenAI, and Spotify to create personalized music experiences
We've all been there: trying to find the perfect playlist that matches exactly how we're feeling. Maybe you're "feeling nostalgic about rainy summer days" or need "upbeat focus music to power through a deadline." Traditional playlist searches just don't capture these nuanced emotional states.
That's why I built a Mood-Based Playlist Generatorβan API that combines the intelligence of OpenAI's language models with Spotify's vast music library to create personalized playlists based on mood descriptions. In this article, I'll walk you through how I built it, the challenges I faced, and how you can create your own.
The idea was simple but powerful: what if you could describe exactly how you're feeling, and AI would curate the perfect soundtrack? No more endless scrolling through generic playlists or spending hours creating your own.
My application bridges three key components:
The application flow works like this:
Let's break down the key components of the code:
The first challenge was implementing Spotify's OAuth flow, which requires several steps:
def get_spotify_auth_url(): scope = "playlist-modify-private playlist-modify-public user-read-private" auth_url = f"https://accounts.spotify.com/authorize?client_id={SPOTIFY_CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&scope={scope}" return auth_url def access_token(auth_code): auth_header = base64.b64encode(f"{SPOTIFY_CLIENT_ID}:{SPOTIFY_CLIENT_SECRET}".encode()).decode() # Request token from Spotify...
This gives our application permission to create playlists in the user's Spotify account.
The heart of the application is the mood interpretation. I use OpenAI's models to translate a mood description into concrete song suggestions:
def generate_song_queries(mood_description, num_songs=10): prompt = f""" Generate {num_songs} specific song search queries based on the following mood description: "{mood_description}" Each query should be a SIMPLE search term without special formatting. For example: "Adele Hello" or "Ed Sheeran Shape of You" """ response = openai.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are a music expert that suggests songs matching specific moods."}, {"role": "user", "content": prompt} ], response_format={"type": "json_object"} )
This approach leverages OpenAI's understanding of both language and music culture to generate relevant song suggestions. The model remarkably understands the emotional tones that certain artists and songs evoke.
With song suggestions in hand, the API then:
One of the most frustrating bugs was with the Spotify authentication. The error message "Only valid bearer authentication supported" kept appearing.
The fix was surprisingly simple but easy to miss: the token formatting had extra spaces. This taught me the importance of clean auth token handling:
# Properly format the access token by removing any extra spaces or quotes if access_token: access_token = access_token.strip() if access_token.startswith('"') and access_token.endswith('"'): access_token = access_token[1:-1]
Getting the right song suggestions required careful prompt design. Initially, I was getting songs that were too obscure or didn't match the mood well. The solution was to be more specific in the prompt:
Generate {num_songs} specific song search queries based on the following mood description:
"{mood_description}"
Each query should be a SIMPLE search term without special formatting.
This illustrates how critical prompt engineering is when working with AI models.
The resulting playlists have been surprisingly spot-on. For example:
Mood: "Nostalgic about the early 2000s but feeling optimistic"
Result: A mix of 2000s hits with upbeat, forward-looking tracks
Mood: "Need focus but feeling creative and slightly rebellious"
Result: A blend of instrumental focus music with creative, boundary-pushing tracks
Want to create your own mood-based playlist generator? Here's how to get started:
Set up your environment:
pip install fastapi uvicorn python-dotenv requests openai
Create developer accounts:
Clone the repository and set up your environment variables:
SPOTIFY_CLIENT_ID=your_spotify_client_id
SPOTIFY_CLIENT_SECRET=your_spotify_client_secret
OPENAI_API_KEY=your_openai_api_key
REDIRECT_URI=http://localhost:8888/callback
The repo: https://github.com/Chukwuebuka-2003/mood-playlist-ai
python api.py
This project is just the beginning of what's possible at the intersection of AI and music. Future enhancements could include:
In an age of algorithmic recommendations, there's something powerful about describing your exact emotional state and getting music that resonates. This project shows how AI can help create deeply personalized experiences that connect with us on an emotional level.
Music has always been about emotion, and now technology is helping us bridge the gap between what we feel and what we hear. The code for this project is available on GitHub, and I welcome contributions and ideas for how to make this emotional-musical connection even stronger.
Have you ever wanted a playlist that perfectly matches your mood? What moods would you want to translate into music? Share your thoughts in the comments!