Why Listening Trends Matter

In the previous lesson, you explored how the dashboard interacts with your backend — browsing tracks, logging listens, and viewing recommendations. Now, we shift to a new backend feature: the listening trends API.

  • For users: Trends provide quick insights into their listening habits (mood, tempo, energy).
  • For the smart system: Trends are key for session-aware recommendations, as they help the model adapt to current user preferences.

In this unit, we’ll add a new endpoint, /api/trends/<user_id>, and implement trend analysis in a new session_analysis.py module.

The Core Logic: get_recent_session_trends

The heavy lifting is done by the get_recent_session_trends function in src/session_analysis.py. Its job is to look at a user’s last N sessions (default 5) and extract three key statistics:

  • Most common mood – The mood that appears most frequently in recent tracks.
  • Average tempo – The mean tempo of those tracks.
  • Average energy – The mean energy value (on a 0–1 scale) for the same set.

Code Breakdown

What’s happening here?

  • It reads sessions.csv to get all listening events.
  • Filters only the sessions for the given user_id.
  • Sorts them by time and picks the most .
The Trends API Endpoint

The function is exposed to the frontend through this new route in app.py:

Key points:

  • When a GET request hits /api/trends/<user_id>, it fetches trend data for that user.
  • If no sessions are found, it returns an empty trends object with a message.
  • If something goes wrong, it safely returns a 500 error.

Example Request: GET /api/trends/user123

Example Response:

Frontend Integration

The dashboard already includes a "Trends" button that calls this route:

  • When you click "Trends", the UI requests /api/trends/<user_id> and displays the most common mood across recent sessions. This feature updates in real-time as the user logs more listening sessions.

How to Test It

  • Enter a User ID on the dashboard.
  • Listen to a few tracks (manually or with "Simulate Session").
  • Click "Trends" to see the computed mood.

The displayed stats will reflect only the last 5 sessions (or fewer if fewer sessions exist).

Summary and Practice Preview

In this lesson, you learned how the Music Player analyzes your recent listening sessions to find trends. You saw how the app collects session data, how the get_recent_session_trends function works, and how the /api/trends/<user_id> endpoint provides this information.

Next, we’ll move toward session-aware recommendations, where these trend metrics will influence which tracks are suggested to the user.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal