Welcome back! In the previous lessons, you learned how to set up a backend for a music player app and how to serve track data through API endpoints. Now, let’s take the next step: tracking when users listen to tracks.
Tracking listening sessions is important for many reasons. It helps you understand user behavior, recommend new music, and even reward users for their activity. In real-world music apps, every time you play a song, the app records that event somewhere. In this lesson, you will learn how to log these listening sessions in your own app.
Before we dive into session tracking, let’s quickly remind ourselves of the current setup. You already have a Flask app that loads track data from a JSON file and serves it through API endpoints. Here’s a quick look at how the app and data are set up:
This setup allows you to retrieve all tracks or a single track by its ID. We will build on this foundation to add session tracking.
To log a listening session, you first need to make sure the track exists. This is done by accessing the track data. Here’s how you can get all tracks or a specific track by ID:
Explanation:
load_tracks_data()loads the track data from a JSON file and caches it for faster access.get_all_tracks()returns all tracks as a DataFrame.get_track_by_id(track_id)looks up a track by its ID and returns its details as a dictionary, orNoneif not found.
This is important because, before logging a session, you want to make sure the track actually exists.
Now, let’s see how to record a listening session. The goal is to save each session (user, track, timestamp, and source) in a CSV file. Here’s the function that does this:
Explanation:
- The function starts by checking if the track exists using
get_track_by_id. - It defines the field names for the CSV file, which include:
user_id,track_id,timestamp, andsource. - It checks if the CSV file is missing or empty — if so, it writes a header row.
- It appends a new row with the session data: the user who listened, the track that was played, the timestamp of the session, and the source (which is "api").
- It returns a success message if the write is successful, or an error if something goes wrong.
Example Output: If you call and the track exists, a new line like this will be added to :
To make this feature available to users, you need an API endpoint that receives session log requests and calls the logging function. Here’s how it’s done:
Explanation:
- This endpoint listens for POST requests at
/api/listen/<user_id>/<track_id>. - It calls
log_listening_session()with the provided user and track IDs. - If the session is logged successfully, it returns a success message and a 201 status code.
- If there’s an error (like the track not being found), it returns an error message and the appropriate status code.
Example Output:
A successful request will return:
If the track does not exist, you’ll get:
Let’s take a closer look at how your Flask route and logging function work together behind the scenes to create a listening session.
You now have two connected parts in your backend:
- The database function:
log_listening_session(user_id, track_id)This function lives indatabase.pyand is responsible for:
- Validating the track exists
(using get_track_by_id) - Opening or creating
sessions.csv - Writing the session data
(user, track, timestamp) - Returning success or error status
It contains all the core business logic around session tracking. It makes no assumptions about how it’s called — which makes it reusable by other parts of your app (e.g., APIs or internal tools).
- The Flask route:
/api/listen/<user_id>/<track_id>This route lives inapp.py. Its job is to:
- Receive a POST request from the outside world
- Extract the user_id and track_id from the URL
- Pass them to
log_listening_session(...) - Format the return message into a valid HTTP response (JSON + status code)
You can test your session logging route using curl in your terminal. Here's a sample POST request:
Now that you're logging listening sessions, let’s take it one step further — what if you want to know how many times each track has been played?
This is common in real apps for generating “Top Charts” or personalized recommendations.
Here’s a function that counts how many times each track appears in the sessions.csv file:
You can expose it with a new route like this:
A request to curl -s http://localhost:5001/api/listens/counts might return:
In this lesson, you learned how to track when a user listens to a track by:
- Checking if the track exists
- Logging the session to a CSV file with the user, track, and timestamp
- Creating an API endpoint to handle session logging requests
These are the basic building blocks for tracking user activity in a music app. In the next set of exercises, you’ll get hands-on practice with logging sessions and working with the API. This will help you reinforce what you’ve learned and prepare you for more advanced features in future lessons.
