<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Spotify - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Spotify - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 26 May 2026 10:37:14 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/spotify/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ API Testing with Postman: A Step-by-Step Guide Using the Spotify API ]]>
                </title>
                <description>
                    <![CDATA[ 🎯 The Objective In this guide, I’ll introduce you to Postman, a popular API development and testing tool. If you are a beginner mainly focused on frontend development, you may not have had much experience fetching data from an API. And in that case ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/api-testing-with-postman-a-step-by-step-guide-using-the-spotify-api/</link>
                <guid isPermaLink="false">66e1d20cbe8f281fa6f7660a</guid>
                
                    <category>
                        <![CDATA[ Postman ]]>
                    </category>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ API basics  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Spotify ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Matthes B. ]]>
                </dc:creator>
                <pubDate>Wed, 11 Sep 2024 17:23:24 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/uv5_bsypFUM/upload/ef5e3375e4ea08db6b5addd47afbc82f.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-the-objective"><strong>🎯</strong> The Objective</h2>
<p>In this guide, I’ll introduce you to Postman, a popular API development and testing tool.</p>
<p>If you are a beginner mainly focused on frontend development, you may not have had much experience fetching data from an API. And in that case you probably haven't encountered many situations where you need to make multiple requests to an API for testing purposes during your development process.</p>
<p>But understanding how to test APIs and connect with them via Postman or similar tools will become important at some point in your career. If you decide to venture into backend development, understanding these concepts is essential.</p>
<p>After covering some basic information about Postman and the Spotify API documentation, we’ll dive into more key Postman features. Then, we’ll select one Spotify endpoint and walk through the process of making requests to it.</p>
<h2 id="heading-heres-what-well-cover"><strong>🔐 Here's What We'll Cover</strong></h2>
<ul>
<li><p>You'll gain fundamental knowledge of working with Postman.</p>
</li>
<li><p>You'll strengthen your ability to work with APIs and their documentation.</p>
</li>
<li><p>You'll explore the basics of the public Spotify API.</p>
</li>
</ul>
<h2 id="heading-prerequisites"><strong>📝</strong> Prerequisites</h2>
<ul>
<li><p>You should have a basic understanding of APIs.</p>
</li>
<li><p>You don't need any prior knowledge of Postman.</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-exploring-the-spotify-api-with-postman">Exploring the Spotify API with Postman</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-postman-experience">The Postman Experience</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-make-your-first-request-to-the-spotify-api">How to Make Your First Request to the Spotify API</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-spotify-api-authorization">Spotify API Authorization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-spotify-api-authorization-scopes">Spotify API Authorization Scopes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ol>
<h2 id="heading-exploring-the-spotify-api-with-postman">Exploring the Spotify API with Postman</h2>
<p>To get a brief overview of what Postman is, let's refer to the following explanation from ChatGPT:</p>
<blockquote>
<p>"Postman is a popular API (Application Programming Interface) development and testing tool that simplifies working with APIs by providing an easy-to-use interface for sending HTTP requests and receiving responses. It's widely used by developers, QA engineers, and teams who work with APIs to ensure they function correctly and efficiently."</p>
</blockquote>
<p>While we will focus on making HTTP requests, it's important to note that Postman is also versatile and can be used to work with GraphQL, gRPC, WebSocket, Socket.IO, and MQTT.</p>
<p>With Postman in hand, we need an API endpoint to test. For this, we’ll use the public Spotify API, which offers a variety of endpoints for different use cases. This can even be an exciting opportunity for your next project if you're a beginner looking for a fun project to explore.</p>
<p>The <a target="_blank" href="https://developer.spotify.com/documentation/web-api">Spotify Web API</a> is professionally designed, offering all the necessary information for developers. With their "Overview" and "Getting Started" sections, it's straightforward to follow along, even for beginners.</p>
<p>While learning the basics of Postman, we will explore key parts of the Spotify API documentation necessary for successful API testing. For instance, we will demonstrate how to make an HTTP request to the endpoint for <a target="_blank" href="https://developer.spotify.com/documentation/web-api/reference/get-playlist">retrieving data from a playlist</a>.</p>
<p>But first, let’s cover some Postman fundamentals.</p>
<h2 id="heading-the-postman-experience">The Postman Experience</h2>
<p>You can use Postman in a number of different ways. In my case, I'm using the <a target="_blank" href="https://www.postman.com/downloads/">desktop version</a> of Postman.</p>
<p>But you can also use Postman directly in your browser, or even via the Postman CLI (Command Line Interface). There's also an official Postman extension for VS Code. You can find these versions through the link I just shared.</p>
<p>If you're completely new to Postman, you may want to start with the web version or the downloadable desktop version, especially if you plan to use Postman regularly in the future.</p>
<p>After starting the desktop version of Postman, the first thing you’ll see is this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725784802934/f999e51b-13d1-4bfc-b51a-99cf16c51209.png" alt="Initial Postman interface view" class="image--center mx-auto" width="1908" height="1021" loading="lazy"></p>
<p>This might look slightly different from what you see initially. I already have an account. You may need to create one first for free. You also may need to create a workspace first. In my case, I’m already inside the "My Workspace" workspace.</p>
<p>In the upper left corner, you'll find several tabs, including "Collections", "Environments", "History", and an icon to configure this sidebar.</p>
<p>For now, we’ll stay on the "Collections" tab and click on "Create Collection":</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725785048909/3751a2a7-c583-4918-ba92-b14ddf09787c.png" alt="Creating a new collection in Postman" class="image--center mx-auto" width="547" height="568" loading="lazy"></p>
<p>Once you click on that, your focus will shift to the name of the collection in the top center. By typing, you can rename your collection from "New Collection" to something more appropriate for your specific use case.</p>
<p>For this case, I named the collection "Spotify API":</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725785166414/65ae8c54-be76-4b70-99b1-87897ef0506d.png" alt="Viewing a created collection in Postman" class="image--center mx-auto" width="1623" height="450" loading="lazy"></p>
<p>Now, we have a collection, but what exactly is that? A collection is essentially a space to organize multiple request structures. This will become clearer once we add our first HTTP request. You can do this by clicking on the blue text that says "Add a request":</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725785355577/2b7cb0ea-9fe4-41e5-a0b4-a01472a6c4b5.png" alt="Creating the first request within a collection in Postman" class="image--center mx-auto" width="289" height="92" loading="lazy"></p>
<p>When you do that, your focus will again be on the name of the element. If you type something now, you can rename the request from "New Request" to something more appropriate for the situation. In this case, since I’m not sure which request I want to create yet, I'll simply call it "test" for now.</p>
<p>If you'd like to create another request at this point, you can click on the three dots to the right of the collection's name (the 6th option):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725785494545/227bad55-040f-45c4-8afc-5fb978714d53.png" alt="Creating new requests within a collection in Postman" class="image--center mx-auto" width="286" height="729" loading="lazy"></p>
<p>There are multiple options you can choose from, with "Add request" being one of them.</p>
<p>At this point, we've created a collection within our workspace, and inside that collection, we've added an HTTP request. You can have multiple collections, each containing multiple requests. This helps organize your requests, especially when you reach a point where having one large list of pre-configured requests becomes cumbersome to manage.</p>
<p>On the newly created HTTP request, we can see some details:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725785740673/b7d66a0d-d16c-4cf5-846b-21c0289e1fc9.png" alt="Viewing a created HTTP request in Postman" class="image--center mx-auto" width="1474" height="280" loading="lazy"></p>
<p>The first thing you might notice is the HTTP request method, which is set to "GET" by default. If you click on "GET" with the downward arrow, you can choose from various methods or even type in your own if needed.</p>
<p>To the right of that, there’s a text field where you'll enter your API’s URL along with its endpoint (we'll try this shortly).</p>
<p>Below, there are several important tabs. Right now, we're on the "Params" tab. Here, you can add key-value pairs that will directly modify the request you're making. These are called Query Params, which you may have encountered before. For example, if your URL is <code>https://google.com</code>, adding a key-value pair as a Query Param might look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725786057766/5c379d02-a1db-4484-9951-17d8fc63d9f5.png" alt="Adding Query Params to a HTTP request in Postman" class="image--center mx-auto" width="1487" height="286" loading="lazy"></p>
<p>As for Query Params, whether you need them depends on the request you're making. A common use case would be pagination on a website with a table. For example, you might use a query param like "page=4" to specify which page of results you want.</p>
<p>Next is the "Authorization" tab, which handles authentication and authorization for your request. We’ll cover this in more detail later, so we’ll skip it for now.</p>
<p>Then, we have the "Headers" tab, which is crucial because it contains all the information included in your request’s header, such as any authorization data if that’s set up.</p>
<p>Finally, the "Body" tab, located to the right, is also quite important. For instance, if you’re making a POST request to add an item to a database, you’d likely need to send information such as the item’s name or category. This kind of data is often included in the request body in JSON format.</p>
<p>To add JSON-formatted data, you can click on "raw" within the "Body" tab, and then select the format you want (with "JSON" being the default option):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725786376804/334980e7-f2a4-44ec-b354-6923254c842b.png" alt="Viewing the &quot;Body&quot; tab of a HTTP request in Postman" class="image--center mx-auto" width="1489" height="168" loading="lazy"></p>
<p>As with Query Params, the format and data required depend heavily on the API and endpoint you're using. Just keep in mind that you can configure all the necessary options within these tabs.</p>
<p>The remaining two tabs are "Scripts" and "Settings." In the "Scripts" tab, you can add custom code, but this is more advanced and not necessary for our current situation. The "Settings" tab allows for adjustments, though in most cases, you won’t need to modify anything here.</p>
<h2 id="heading-how-to-make-your-first-request-to-the-spotify-api">How to Make Your First Request to the Spotify API</h2>
<p>Now, we’ll make our first actual request using Postman. For this, we can dive into the Spotify API developer documentation, where all endpoints are listed. For this first test, we’ll <a target="_blank" href="https://developer.spotify.com/documentation/web-api/reference/get-playlist">fetch data about a playlist</a>.</p>
<p>In that description, you’ll find a wealth of useful information, including the endpoint and the required data for a successful response. You also have the option to make the request directly from the page after logging in with your Spotify account:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725786874122/dfc15da0-4c9d-465d-8f29-470b7978ed18.png" alt="Viewing the &quot;Get Playlist&quot; Spotify API documentation" class="image--center mx-auto" width="1887" height="909" loading="lazy"></p>
<p>Such extensive API documentation is incredibly helpful and makes it easy to work with, especially for beginners. Keep in mind, though, that not all API documentation is this thorough.</p>
<p>In this case, we can see the endpoint is <code>https://api.spotify.com/v1/playlists/{playlist_id}</code>, with <code>playlist_id</code> being the only required parameter in the curly brackets. You’ll also see optional parameters like <code>market</code>, <code>fields</code>, and <code>additional_types</code>, which can help refine the response. But again, these are optional, and you only need <code>playlist_id</code> for the basic request.</p>
<p>If you want to include optional information, like <code>market</code>, you’d use the Query Params mentioned earlier. For example, adding <code>ES</code> as the market alongside the <code>playlist_id</code> would change the URL to: <code>https://api.spotify.com/v1/playlists/3cEYpjA9oz9GiPac4AsH4n?market=ES</code>.</p>
<p>To make the basic request in Postman (without any optional parameters), we’ll return to our "test" request and enter the URL with the corresponding endpoint:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725787287945/6c54e09f-08c0-4bf9-9dd9-deabe5a24a22.png" alt="Inserting the &quot;Get Playlist&quot; Spotify API endpoint in a HTTP request in Postman" class="image--center mx-auto" width="515" height="54" loading="lazy"></p>
<p>This approach will work, but I recommend another method.</p>
<p>Since we have our Spotify API collection and may want to add multiple requests to that collection, it's a good practice to use variables for sections of the URL or information that will remain consistent across multiple requests. In this case, the base URL, <code>https://api.spotify.com/v1/</code>, will stay the same for all Spotify API requests. Instead of manually adding it to every request, we can create a variable for it.</p>
<p>To do this, we’ll switch to the "Environments" tab in the upper left corner. From there, click on the plus icon to create a new environment:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725787536747/937b306f-1f54-4434-973d-6ba389a865fe.png" alt="Creating a new environment in Postman" class="image--center mx-auto" width="374" height="119" loading="lazy"></p>
<p>We'll name the environment “Spotify API”.</p>
<p>Next, we'll create variables, such as <code>base_url</code>, and assign the appropriate value to it. You can also choose between the type options: <code>default</code> or <code>secret</code>. Since this isn't sensitive data, it can remain set to <code>default</code>. If you choose <code>secret</code>, you'd need to click on an eye icon to reveal the variable’s value each time, otherwise, it would be masked with <code>••••</code>, similar to how passwords are displayed.</p>
<p>Here’s what it looks like so far:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725787778964/02e4bcf5-3f36-47e8-9882-6cdba591e443.png" alt="Creating an environment variable in Postman" class="image--center mx-auto" width="1858" height="233" loading="lazy"></p>
<p>Next, we’ll return to the Spotify API collection and look at the upper right corner, where it currently says "No environment". Click there and select the "Spotify API" environment that we just created:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725787865310/abb97e82-2a6b-4411-a8cd-9e4430e83956.png" alt="Selecting the created environment for the current collection in Postman" class="image--center mx-auto" width="435" height="210" loading="lazy"></p>
<p>Now, we can use the variables from that environment for all the requests within the "Spotify API" collection. To insert a variable, you’ll use double square brackets, like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725788017057/10cd4dbc-fecf-46d7-9789-9c80b1325215.png" alt="Inserting the created environment variable for the HTTP request in Postman" class="image--center mx-auto" width="419" height="55" loading="lazy"></p>
<p>If you receive a message that the variable couldn't be found, make sure to save the "Spotify API" environment. The dots on the right of the tab names indicate that you can save new information by pressing <code>CTRL + S</code>, for example. This step is necessary for the created variable to be recognized.</p>
<p>With the variable in place, you can now modify just this one variable to change the <code>base_url</code> for all your corresponding requests. While this may not seem immediately useful for the <code>base_url</code>, since it likely won’t change anytime soon, variables can be incredibly helpful in other scenarios. This was an opportunity to introduce you to how they work.</p>
<p>Next, I’ll rename the HTTP request from "test" to something more descriptive, like "Playlist," to indicate what this request is about. Along with the "GET" method, it will be clear that this request is for fetching playlist data.</p>
<p>Now that everything is set, let's send the request by clicking the "Send" button on the right while viewing the HTTP request. You’ll see the response appear in the bottom half of the screen:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725788403952/4212378e-c000-4b5c-bdc1-43a5658b1f11.png" alt="Viewing the first response of the sent HTTP request in Postman" class="image--center mx-auto" width="1555" height="259" loading="lazy"></p>
<p>What a bummer, the request wasn’t successful!</p>
<p>This happened because we didn’t provide any authorization. That’s why we received a "401 Unauthorized" error with the message "No token provided".</p>
<p>Since this is a protected endpoint, we need an access token, which you would obtain by logging into Spotify. If you tried making a request on the Spotify API documentation website earlier, you probably noticed that it asked you to log in before sending the request. By doing so, it acquired your session's access token, which is exactly what we need in our situation as well.</p>
<p>However, instead of logging in with our username and password, we’ll use a different authorization method.</p>
<h2 id="heading-spotify-api-authorization">Spotify API Authorization</h2>
<p>To make basic requests to the Spotify API, you'll need an access token, which can be generated using your credentials. This is a common approach with many APIs, where you need to obtain an access token before you can access the endpoints you're targeting.</p>
<p>The Spotify Developer API provides a <a target="_blank" href="https://developer.spotify.com/documentation/web-api/tutorials/getting-started#request-an-access-token">step-by-step guide</a> on how to get your access token.</p>
<p>Following the outlined steps, the first task is to create an application profile, which you can do in just a few seconds, especially for a test project:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725824014786/22229e4f-0605-488b-80ef-72034fd8a414.png" alt="Viewing the created &quot;test&quot; application in the Spotify API Developers dashboard" class="image--center mx-auto" width="1521" height="385" loading="lazy"></p>
<p>After completing this step, we can proceed by clicking on the "test" project to navigate to the "Settings" of the project. Here, you'll find the "Client ID" and "Client Secret":</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725824076709/5adfd96a-f7e9-45e8-9dcf-67137ef2c814.png" alt="Viewing detailed information for the created &quot;test&quot; application in the Spotify API Developers dashboard" class="image--center mx-auto" width="1562" height="757" loading="lazy"></p>
<p>Keep in mind that this information is generally considered sensitive, so you should avoid sharing it publicly (in most cases). But since this is just a test project, which will be deleted by the time this guide is published, I am showing it to make it easier for you to follow along with my explanations.</p>
<p>With your Client ID and Client Secret in hand, you now have the information needed to request an access token. These access tokens are used to authorize yourself when interacting with API endpoints.</p>
<p>You can kinda compare this to logging into software, where you need to authenticate yourself before accessing certain information. In such cases, it’s likely that an access token is generated for the duration of your session to authorize your requests to the software’s backend API.</p>
<p>Also, remember that access tokens change with each login session, meaning you receive a different token every time. Just keep in mind that with our current selected method, we don’t have access to specific user information. Instead, we only can make basic GET requests without acting on the behalf of a user. Later on we will cover this a little more.</p>
<p>The Spotify API documentation is quite helpful and provides detailed instructions on the exact request you need to make. We’ll now jump into Postman for this step.</p>
<p>Go to your "Spotify API" collection and click on the "Authorization" tab. Here, you need to choose the appropriate "Auth Type". There are several options, and the authorization method can differ depending on the API you’re using.</p>
<p>If you already have an access token, you may opt for the "Bearer Token" auth type, where you simply paste the token directly. This is the type of authorization we’ll use in the end. But instead of manually requesting a token and then inputting it into the "Bearer Token" field, we can automate this process. For this, we’ll select "<a target="_blank" href="https://oauth.net/2/">OAuth 2.0</a>" as the auth type.</p>
<p>How did I know "OAuth 2.0" was the right choice? If you check the Spotify API documentation, you’ll find some corresponding information while going through their step-by-step guide. Also, all endpoints that need authorization are tagged with "OAuth 2.0", including the "<a target="_blank" href="https://developer.spotify.com/documentation/web-api/reference/get-playlist">Get Playlist</a>" endpoint:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725971891125/724c447e-3016-42b2-9538-a311933738e6.png" alt="Viewing the needed &quot;Auth Type&quot; for the &quot;Get Playlist endpoint" class="image--center mx-auto" width="332" height="86" loading="lazy"></p>
<p>The documentation also mentions that Spotify uses "Client Credentials" for its tutorial. This is the "grant type" and indicates the information you’ll provide for the authorization request. With "Client Credentials," you pass your Client ID and Client Secret (the information from our test application).</p>
<p>For instance, with the "Password Credentials" grant type, you would also pass a "Username" and "Password," which is used when logging in with an actual user account.</p>
<p>There are other authorization methods as well, and the API documentation usually specifies which approach to use. In our case, since we have the Client ID and Client Secret and don’t need specific user access, we know the "Client Credentials" grant type is the appropriate choice.</p>
<p>When passing your Client ID and Client Secret in Postman, you may receive a suggestion to use variables for this information:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725824602370/d488cb29-6a62-4756-995e-32a018237893.png" alt="Setting up the &quot;Authorization&quot; for the Spotify API collection in Postman" class="image--center mx-auto" width="852" height="835" loading="lazy"></p>
<p>Similar to the <code>base_url</code> variable we used earlier, creating variables for the Client ID and Client Secret can be helpful, especially if you plan to use multiple HTTP requests with similar authorizations. This way, you can reference the same variables in all your requests, and if anything changes, you only need to update the variable in one place.</p>
<p>In this case, we’ll do the same by switching to the "Environments" tab and adding variables for both <code>client_id</code> and <code>client_secret</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725824729649/77ed62b1-7221-4e32-bccf-be366102c3df.png" alt="Adding environment variables for the Client ID and Client Secret" class="image--center mx-auto" width="1581" height="282" loading="lazy"></p>
<p>Next, you’ll insert those variables into the authorization process we started earlier:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725824827178/98394518-2a93-40ca-9e6f-01544ee3bfbb.png" alt="Updating the &quot;Authorization&quot; for the Spotify API collection with environment variables in Postman" class="image--center mx-auto" width="911" height="804" loading="lazy"></p>
<p>Now, we just need to add the token authorization URL, which can be found on the same page as before: <code>https://accounts.spotify.com/api/token</code>. Enter this into the "Access Token URL" field. Then, give the setup a fitting name of your choice and scroll down to click the "Get New Access Token" button:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725824937975/e94e1701-6a4f-43c9-949d-136160a6aeb4.png" alt="Successfully creating an access token in Postman" class="image--center mx-auto" width="1089" height="586" loading="lazy"></p>
<p>It was successful! Now, click on "Proceed" to view more details about the generated access token:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725824969843/f3985bad-e596-4b72-a31f-cf9fc7b49b8d.png" alt="Viewing detailed information about the created access token in Postman" class="image--center mx-auto" width="910" height="466" loading="lazy"></p>
<p>With our access token ready, click on "Use Token" in the upper right, and Postman will confirm that the token has been added.</p>
<p>Now, if we switch to the "Playlist" GET request we created earlier, you’ll see the option to set up an authorization method for this specific request. But since we’ve already set up authorization for the entire collection, simply select "Inherit auth from parent" as the "Auth Type" for this request:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725825052455/c1167201-89b5-4560-8f83-be0a0e39bcea.png" alt="Viewing the &quot;Auth Type&quot; for the HTTP request within the Spotify API collection in Postman" class="image--center mx-auto" width="1598" height="456" loading="lazy"></p>
<p>Postman will indicate which authorization type is being used and where it’s coming from. In this case, it will say: "The request is using OAuth 2.0 from collection Spotify API."</p>
<p>Next, if we switch to the "Headers" tab and click on "8 hidden," we can see an "Authorization" key. By clicking on the eye symbol to the right, we can reveal this information.</p>
<p>If you compare this with the access token we just generated, you'll notice they are the same (with "Bearer" in front of the actual access token). When you create a new token for the collection, as we did earlier, this information updates automatically.</p>
<p>With everything set up, we are now ready to send the request we tried earlier, this time with a valid access token in the "Authorization" header.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725825252369/eedff426-4843-4e63-8022-28ca6f783f8a.png" alt="Inspecting the &quot;Headers&quot; tab of the HTTP request in Postman" class="image--center mx-auto" width="1085" height="423" loading="lazy"></p>
<p>And if we now hit "Send", we will get a response like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725905470563/ac771bf6-a278-4564-8360-6397b01ea05c.png" alt="Viewing the JSON response of the sent HTTP request in Postman" class="image--center mx-auto" width="1505" height="600" loading="lazy"></p>
<p>The response is a JSON object containing a lot of information to explore. You can do this for your own playlist as well, as long as it’s set to public on Spotify.</p>
<p>To give another example, I’ll go to Spotify, use the "Share" option for my playlist, and copy the playlist link, which looks like this: <code>https://open.spotify.com/playlist/1OPgvkPckzXm9SB0CIJf3o?si=cbe9c361f8024abd</code>.</p>
<p>The part we’re interested in is the playlist ID, which is found after the last forward slash and before the question mark—in this case, <code>1OPgvkPckzXm9SB0CIJf3o</code>. We’ll replace the current playlist ID with this one in Postman:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725905870964/588a8569-b8b3-48f4-98c6-3bf1cb636dd1.png" alt="Adjusting the &quot;Playlist ID&quot; for the HTTP request in Postman" class="image--center mx-auto" width="460" height="61" loading="lazy"></p>
<p>Now, if we hit "Send," we’ll receive the corresponding JSON response:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725905937409/3dd3c6b2-cacb-4a1c-9f2b-687772b34fae.png" alt="Inspecting the JSON response of the adjusted HTTP request in Postman" class="image--center mx-auto" width="799" height="378" loading="lazy"></p>
<p>This response is also a large JSON object with plenty of data to explore.</p>
<p>And that's it! We've successfully configured a fundamental Postman setup with an HTTP GET request, including authorization, to fetch data from the Spotify API.</p>
<h2 id="heading-spotify-api-authorization-scopes">Spotify API Authorization Scopes</h2>
<p>By now, we’ve successfully used authorization with our Client ID and Client Secret. But if you dive deeper into the Spotify API documentation, you’ll find situations where this method of authorization is insufficient for certain actions.</p>
<p>While fetching playlist data and other GET requests work with Client ID and Client Secret authorization, you may encounter endpoints that use POST, PUT, or DELETE methods.</p>
<p>For example, adding new songs to a playlist requires more than just Client ID and Client Secret authorization. You need to authenticate as the actual user associated with the playlist.</p>
<p>In such cases, the documentation lists "Authorization scopes" that define the required permissions. For instance, "playlist-modify-public" and "playlist-modify-private" scopes are needed for modifying public and private playlists, respectively:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725972202770/5109da66-792a-4430-855c-9c6db4d06105.png" alt="Recognizing the mentioned &quot;Authorization scopes&quot; for the &quot;Add Items to Playlist&quot; endpoint in the Spotify API" class="image--center mx-auto" width="405" height="235" loading="lazy"></p>
<p>If you review the Spotify API documentation, you’ll see that it outlines four main authorization methods:</p>
<ul>
<li><p><a target="_blank" href="https://developer.spotify.com/documentation/web-api/tutorials/code-flow">Authorization code</a></p>
</li>
<li><p><a target="_blank" href="https://developer.spotify.com/documentation/web-api/tutorials/code-pkce-flow">Authorization code with PKCE extension</a></p>
</li>
<li><p><a target="_blank" href="https://developer.spotify.com/documentation/web-api/tutorials/client-credentials-flow">Client credentials</a></p>
</li>
<li><p><a target="_blank" href="https://developer.spotify.com/documentation/web-api/tutorials/implicit-flow">Implicit grant</a></p>
</li>
</ul>
<p>The Client credentials method (which we used) does not provide access to user-specific data. To perform actions on behalf of a user, such as modifying their playlists, the "Authorization code" method is required.</p>
<p>In real-world projects, you would typically implement this as part of your app's authentication and authorization process when users log in. For instance, in Next.js projects, NextAuth offers a Spotify login mechanism that simplifies this process.</p>
<p>Alternatively, you could manually handle the necessary requests during the authentication process and add relevant data to the session information.</p>
<p>This topic goes beyond the scope of this guide, as it deals with general authorization and authentication flows for the Spotify API (and other APIs) rather than Postman-specific use cases. But the Spotify API documentation provides valuable resources if you’re interested in exploring more advanced testing with Postman. They also provide a <a target="_blank" href="https://developer.spotify.com/documentation/web-api/howtos/web-app-profile">how-to guide</a> on retrieving a user's profile data and displaying it in your frontend application.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this guide, we covered the fundamentals of Postman: how to set up your first workspace with a collection, create an HTTP request, use variables to simplify the process for future requests, and add authorization logic to obtain an access token required for making requests. All of this was demonstrated using the Spotify API, which provides extensive documentation on accessing its endpoints.</p>
<p>From here, you might want to explore deeper by learning how to access Spotify API endpoints that require user-specific access information, combined with specific scopes, such as adding new songs to a Spotify playlist.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Spotify’s “This Is” playlists: the ultimate song analysis for 50 mainstream artists ]]>
                </title>
                <description>
                    <![CDATA[ By James Le Each artist has their own unique musical styles. From Ed Sheeran who devotes his life to the acoustic guitar, to Drake who masters the art of rapping. From Adele who can belt some crazy high notes on her pop ballads, to Kygo who creates E... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/spotifys-this-is-playlists-the-ultimate-song-analysis-for-50-mainstream-artists-491882081819/</link>
                <guid isPermaLink="false">66c35f58c7095d76345eb011</guid>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data visualization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ music ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Spotify ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 27 Jun 2018 15:32:31 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*VoHx2GEJLinEv3AWbxHNOw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By James Le</p>
<p>Each artist has their own unique musical styles. From Ed Sheeran who devotes his life to the acoustic guitar, to Drake who masters the art of rapping. From Adele who can belt some crazy high notes on her pop ballads, to Kygo who creates EDM magic on his DJ set. Music is about creativity, originality, inspiration, and feelings, and it is the perfect gateway to connect people across differences.</p>
<p>Spotify is the largest music streaming service available. With more than 35 million songs and 170 million monthly active users, it is the ideal platform for musicians to reach their audience. On the app, music can be browsed or searched via various parameters — such as artists, album, genre, playlist, or record label. Users can create, edit, and share playlists, share tracks on social media, and make playlists with other users.</p>
<p>Additionally, Spotify launched a variety of interesting playlists tailor-made for its users, of which I most admire these three:</p>
<ul>
<li><strong>Discover Weekly</strong>: a weekly generated playlist (updated on Mondays) that brings users two hours of custom-made music recommendations, mixing a user’s personal taste with songs enjoyed by similar listeners.</li>
<li><strong>Release Radar</strong>: a personalized playlist that allows users to stay up-to-date on new music released by artists they listen to the most.</li>
<li><strong>Daily Mix</strong>: a series of playlists that have “near endless playback” and mixes the user’s favorite tracks with new, recommended songs.</li>
</ul>
<p>I recently discovered the <a target="_blank" href="https://open.spotify.com/search/playlists/this%20is%20">‘This Is”</a> playlist series. One of Spotify’s best original features, “This Is” delivers on a major promise of the streaming revolution — the canonization and preservation of great artists’ repertoires for future generations to discover and appreciate.</p>
<p>Each one is dedicated to a different legendary artist, chronicling the high points of iconic discographies. “This is: Kanye West”. “This is: Maroon 5”. “This is: Elton John”. Spotify has provided a shortcut, giving us curated lists of the greatest songs from the greatest artists.</p>
<h3 id="heading-what-well-cover-here">What we’ll cover here</h3>
<p>The purpose of this project is to analyze the music that different artists on Spotify produce. The focus will be placed on disentangling the musical taste of 50 different artists from a wide range of genres. Throughout the process, I also identify different clusters of artists that share a similar musical style.</p>
<p>For the study, I will access the <a target="_blank" href="https://beta.developer.spotify.com/web-api/">Spotify Web API</a>, which provides data from the Spotify music catalog. This can be accessed via standard HTTPS requests to an API endpoint.</p>
<p>The Spotify API provides, among other things, track information for each song, including audio statistics such as <strong>danceability</strong>, <strong>instrumentalness</strong>, or <strong>tempo</strong>. Each feature measures an aspect of a song. Detailed information on how each feature is calculated can be found in the Spotify API Website. The code snippets in this article might be a bit tricky to understand, especially for data beginners, so bear with me.</p>
<p>Here’s a quick summary of my approach:</p>
<ul>
<li>Get the data from Spotify API.</li>
<li>Process the data to extract audio features for each artist.</li>
<li>Visualize the data using D3.js.</li>
<li>Apply k-means clustering to separate the artists into different groups.</li>
<li>Analyze each feature for all the artists.</li>
</ul>
<p>Let’s now retrieve the audio feature information from “This Is” Playlists of 50 different artists on Spotify.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*BVAvpWWBCjB0xHPM_HC1BQ.png" alt="Image" width="800" height="224" loading="lazy">
_Source: [https://blog.prototypr.io/have-you-heard-about-the-spotify-web-api-8e8d1dac9eaf](https://blog.prototypr.io/have-you-heard-about-the-spotify-web-api-8e8d1dac9eaf" rel="noopener" target="<em>blank" title=")</em></p>
<h3 id="heading-getting-data"><strong>Getting data</strong></h3>
<p>The first step was registering my application in the <a target="_blank" href="https://beta.developer.spotify.com/web-api/">API Website</a> and getting the keys (Client ID and Client Secret) for future requests.</p>
<p>The Spotify Web API has different URIs (Uniform Resource Identifiers) to access playlists, artists, or tracks information. Consequently, the process of getting data must be divided into two key steps:</p>
<ul>
<li>get the “This Is” Playlist Series for multiple musicians.</li>
<li>get the audio features for each artist’s Playlist tracks.</li>
</ul>
<h4 id="heading-web-api-credentials"><strong>Web API credentials</strong></h4>
<p>First, I created two variables for the <code>Client ID</code> and the <code>Client Secret</code> credentials.</p>
<pre><code>spotifyKey &lt;- <span class="hljs-string">"YOUR CLIEND ID"</span>spotifySecret &lt;- <span class="hljs-string">"YOUR CLIENT SECRET"</span>
</code></pre><p>After that, I requested an access token in order to authorize my app to retrieve and manage Spotify data.</p>
<pre><code>library(Rspotify)library(httr)library(jsonlite)spotifyEndpoint &lt;- oauth_endpoint(NULL, <span class="hljs-string">"https://accounts.spotify.com/authorize"</span>,<span class="hljs-string">"https://accounts.spotify.com/api/token"</span>)
</code></pre><pre><code>spotifyToken &lt;- spotifyOAuth(<span class="hljs-string">"Spotify Analysis"</span>, spotifyKey, spotifySecret)
</code></pre><h4 id="heading-this-is-playlist-series"><strong>“This Is” Playlist Series</strong></h4>
<p>The first step was to pull the artists’ <a target="_blank" href="https://open.spotify.com/search/playlists/this%20is%20">“This Is” series</a> is to get the URIs for each one. Here are the 50 musicians I have chosen, using their popularity, modernity, and diversity as the main criteria:</p>
<ul>
<li><strong>Pop</strong>: Taylor Swift, Ariana Grande, Shawn Mendes, Maroon 5, Adele, Justin Bieber, Ed Sheeran, Justin Timberlake, Charlie Puth, John Mayer, Lorde, Fifth Harmony, Lana Del Rey, James Arthur, Zara Larsson, Pentatonix.</li>
<li><strong>Hip-Hop / Rap</strong>: Kendrick Lamar, Post Malone, Drake, Kanye West, Eminem, Future, 50 Cent, Lil Wayne, Wiz Khalifa, Snoop Dogg, Macklemore, Jay-Z.</li>
<li><strong>R &amp; B</strong>: Bruno Mars, Beyonce, Enrique Iglesias, Stevie Wonder, John Legend, Alicia Keys, Usher, Rihanna.</li>
<li><strong>EDM / House</strong>: Kygo, The Chainsmokers, Avicii, Marshmello, Calvin Harris, Martin Garrix.</li>
<li><strong>Rock</strong>: Coldplay, Elton John, One Republic, The Script, Jason Mraz.</li>
<li><strong>Jazz</strong>: Frank Sinatra, Michael Buble, Norah Jones.</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*-IcwnYFk40BgckbA4uGbyg.png" alt="Image" width="800" height="400" loading="lazy">
_Source: [http://www.thedrum.com/news/2017/11/29/spotify-wraps-up-2017-making-humorous-goals-2018-using-its-data-and-artists](http://www.thedrum.com/news/2017/11/29/spotify-wraps-up-2017-making-humorous-goals-2018-using-its-data-and-artists" rel="noopener" target="<em>blank" title=")</em></p>
<p>I basically went to each musician’s individual playlist, copied the URIs, stored each URI in a .csv file, and imported the .csv files into R.</p>
<pre><code>library(readr)
</code></pre><pre><code>playlistURI &lt;- read.csv(<span class="hljs-string">"this-is-playlist-URI.csv"</span>, header = T, sep = <span class="hljs-string">";"</span>)
</code></pre><p>With each Playlist URI, I applied the <code>getPlaylistSongs</code> from the “RSpotify” package, and stored the Playlist information in an empty data.frame.</p>
<pre><code># Empty dataframePlaylistSongs &lt;- data.frame(PlaylistID = character(),                            Musician = character(),                            tracks = character(),                            id = character(),                            popularity = integer(),                            artist = character(),                            artistId = character(),                            album = character(),                            albumId = character(),                            stringsAsFactors=FALSE)
</code></pre><pre><code># Getting each playlistfor (i <span class="hljs-keyword">in</span> <span class="hljs-number">1</span>:nrow(playlistURI)) {  i &lt;- cbind(PlaylistID = <span class="hljs-keyword">as</span>.factor(playlistURI[i,<span class="hljs-number">2</span>]),             Musician = <span class="hljs-keyword">as</span>.factor(playlistURI[i,<span class="hljs-number">1</span>]),             getPlaylistSongs(<span class="hljs-string">"spotify"</span>,                              playlistid = <span class="hljs-keyword">as</span>.factor(playlistURI[i,<span class="hljs-number">2</span>]),                              token=spotifyToken))  PlaylistSongs &lt;- rbind(PlaylistSongs, i)}
</code></pre><h4 id="heading-audio-features"><strong>Audio features</strong></h4>
<p>First, I wrote a formula (<code>getFeatures</code>) that extracts the audio features for any specific ID stored as a vector.</p>
<pre><code>getFeatures &lt;- <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">vector_id, token</span>) </span>{  link &lt;- httr::GET(paste0(<span class="hljs-string">"https://api.spotify.com/v1/audio-features/?ids="</span>,   vector_id), <span class="hljs-attr">httr</span>::config(token = token))  list &lt;- httr::content(link)  <span class="hljs-keyword">return</span>(list)}
</code></pre><p>Next, I included <code>getFeatures</code> in another formula (<code>get_features</code>). The latter formula extracts the audio features for the track ID’s vector, and returns them in a data.frame.</p>
<pre><code>get_features &lt;- <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">x</span>) </span>{  getFeatures2 &lt;- getFeatures(vector_id = x, token = spotifyToken)  features_output &lt;- <span class="hljs-keyword">do</span>.call(rbind, lapply(getFeatures2$audio_features, data.frame, stringsAsFactors=FALSE))}
</code></pre><p>Using the formula created above, I was able to extract the audio features for each track. In order to do so, I needed a vector containing each track ID. The rate limit for the Spotify API is 100 tracks, so I decided to create a vector with track IDs for each musician.</p>
<p>Next, I applied the <code>get_features</code> formula to each vector, obtaining the audio features for each musician.</p>
<p>After that, I merged each musician’s audio features data.frame into a new one, <code>all_features</code>. It contains the audio features for all the tracks in every musician’s “This Is” Playlist.</p>
<pre><code>library(gdata)
</code></pre><pre><code>all_features &lt;- combine(TaylorSwift,ArianaGrande,KendrickLamar,ShawnMendes,Maroon5,PostMalone,Kygo,TheChainsmokers,Adele,Drake,JustinBieber,Coldplay,KanyeWest,BrunoMars,EdSheeran,Eminem,Beyonce,Avicii,Marshmello,CalvinHarris,JustinTimberlake,FrankSinatra,CharliePuth,MichaelBuble,MartinGarrix,EnriqueIglesias,JohnMayer,Future,EltonJohn,FiftyCent,Lorde,LilWayne,WizKhalifa,FifthHarmony,LanaDelRay,NorahJones,JamesArthur,OneRepublic,TheScript,StevieWonder,JasonMraz,JohnLegend,Pentatonix,AliciaKeys,Usher,SnoopDogg,Macklemore,ZaraLarsson,JayZ,Rihanna)
</code></pre><p>Finally, I computed the mean of each musician’s audio features using the <code>aggregate</code> function. The resulting data.frame contains the audio features for each musician, expressed as the mean of the tracks in their respective playlists.</p>
<pre><code>mean_features &lt;- aggregate(all_features[, c(<span class="hljs-number">1</span>:<span class="hljs-number">11</span>,<span class="hljs-number">17</span>)], list(all_features$source), mean)
</code></pre><pre><code>names(mean_features) &lt;- c(<span class="hljs-string">"Musician"</span>, <span class="hljs-string">"danceability"</span>, <span class="hljs-string">"energy"</span>, <span class="hljs-string">"key"</span>, <span class="hljs-string">"loudness"</span>, <span class="hljs-string">"mode"</span>, <span class="hljs-string">"speechiness"</span>, <span class="hljs-string">"acousticness"</span>, <span class="hljs-string">"instrumentalness"</span>, <span class="hljs-string">"liveness"</span>, <span class="hljs-string">"valence"</span>, <span class="hljs-string">"tempo"</span>, <span class="hljs-string">"duration_ms"</span>)
</code></pre><p>The image below shows a subset of the <code>mean_features</code> data.frame, for your reference.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*wGUAA2LF3YZCDxRR0tkniw.png" alt="Image" width="800" height="391" loading="lazy"></p>
<h4 id="heading-audio-features-description"><strong>Audio features description</strong></h4>
<p>The description of each feature from the <a target="_blank" href="https://beta.developer.spotify.com/web-api/get-audio-features/">Spotify Web API Guidance</a> can be found below:</p>
<ul>
<li><strong>Danceability</strong>: describes the suitability of a track for dancing. This is based on a combination of musical elements including tempo, rhythm stability, beat strength, and overall regularity. A value of 0.0 is least danceable and 1.0 is most danceable.</li>
<li><strong>Energy</strong>: a measure from 0.0 to 1.0, and represents a perceptual measure of intensity and activity. Typically, energetic tracks feel fast, loud, and noisy. For example, death metal has high energy, while a Bach prelude scores low on the scale. Perceptual features contributing to this attribute include dynamic range, perceived loudness, timbre, onset rate, and general entropy.</li>
<li><strong>Key</strong>: the key the track is in. Integers map to pitches using standard Pitch Class notation. E.g. 0 = C, 1 = C♯/D♭, 2 = D, and so on.</li>
<li><strong>Loudness</strong>: the overall loudness of a track in decibels (dB). Loudness values are averaged across the entire track and are useful for comparing the relative loudness of tracks. Loudness is the quality of a sound that is the primary psychological correlate of physical strength (amplitude). Values typical range between -60 and 0 db.</li>
<li><strong>Mode</strong>: indicates the modality (major or minor) of a track, the type of scale from which its melodic content is derived. Major is represented by 1 and minor is 0.</li>
<li><strong>Speechiness</strong>: Speechiness detects the presence of spoken words in a track. The more exclusively speech-like the recording (e.g. talk show, audio book, poetry), the closer to 1.0 the attribute value. Values above 0.66 describe tracks that are probably made entirely of spoken words. Values between 0.33 and 0.66 describe tracks that may contain both music and speech, either in sections or layered, including such cases as rap music. Values below 0.33 most likely represent instrumental music and other non-speech-like tracks.</li>
<li><strong>Acousticness</strong>: a confidence measure from 0.0 to 1.0 of whether the track is acoustic. 1.0 represents high confidence that the track is acoustic.</li>
<li><strong>Instrumentalness</strong>: predicts whether a track contains no vocals. “Ooh” and “aah” sounds are treated as instrumental in this context. Rap or spoken word tracks are clearly “vocal”. The closer the instrumentalness value is to 1.0, the greater likelihood the track contains no vocal content. Values above 0.5 are intended to represent instrumental tracks, but confidence is higher as the value approaches 1.0.</li>
<li><strong>Liveness</strong>: detects the presence of an audience in the recording. Higher liveness values represent an increased probability that the track was performed live. A value above 0.8 provides strong likelihood that the track is live.</li>
<li><strong>Valence</strong>: a measure from 0.0 to 1.0 describing the musical positiveness conveyed by a track. Tracks with high valence sound more positive (for example happy, cheerful, euphoric), while tracks with low valence sound more negative (for example sad, depressed, angry).</li>
<li><strong>Tempo</strong>: the overall estimated tempo of a track in beats per minute (BPM). In musical terminology, tempo is the speed or pace of a given piece, and derives directly from the average beat duration.</li>
<li><strong>Duration_ms</strong>: the duration of the track in milliseconds.</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*q2q_HGP0kkDt3XFNvsTjrQ.jpeg" alt="Image" width="800" height="558" loading="lazy">
_Source: [https://www.engadget.com/2018/02/05/spotify-recommendation-tech-nelson-custom-playlists/](https://www.engadget.com/2018/02/05/spotify-recommendation-tech-nelson-custom-playlists/" rel="noopener" target="<em>blank" title=")</em></p>
<h3 id="heading-data-visualization"><strong>Data Visualization</strong></h3>
<h4 id="heading-radar-charts"><strong>Radar charts</strong></h4>
<p>A radar chart is useful to compare the musical vibes of these musicians in a more visual way. The first visualization is an R implementation of the radar chart from the <a target="_blank" href="http://www.chartjs.org/">chart.js</a> JavaScript library, and evaluates the audio features for ten selected musicians.</p>
<p>In order to plot, I normalized the key, loudness, tempo, and duration_ms values to be from 0 to 1. This helps to make the chart more clear and readable.</p>
<pre><code>mean_features_norm &lt;- cbind(mean_features[<span class="hljs-number">1</span>], apply(mean_features[<span class="hljs-number">-1</span>],<span class="hljs-number">2</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">x</span>)</span>{(x-min(x))/diff(range(x))}))
</code></pre><p>Okay, let’s plot these interactive radar charts in batches of ten musicians. Each chart displays data set labels when you hover over each radial line, showing the value for the selected feature. The code below details the process of making the radar chart for the first batch of ten musicians. The code for the other four batches has been omitted, but the radar charts are displayed.</p>
<p><strong>Batch 1: Taylor Swift, Ariana Grande, Kendrick Lamar, Shawn Mendes, Maroon 5, Post Malone, Kygo, The Chainsmokers, Adele, Drake</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*dbjyWWWkCpbnz5xIRuDudA.png" alt="Image" width="800" height="437" loading="lazy"></p>
<p><strong>Batch 2: Justin Bieber, Coldplay, Kanye West, Bruno Mars, Ed Sheeran, Eminem, Beyonce, Avicii, Marshmello, Calvin Harris</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*eiqCu3agTApjiJuTDNwnTA.png" alt="Image" width="800" height="485" loading="lazy"></p>
<p><strong>Batch 3: Justin Timberlake, Frank Sinatra, Charlie Puth, Michael Buble, Martin Garrix, Enrique Iglesias, John Mayer, Future, Elton John, 50 Cent</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*tHQk1q8_ND7ltSRSarVrNw.png" alt="Image" width="800" height="501" loading="lazy"></p>
<p><strong>Batch 4: Lorde, Lil Wayne, Wiz Khalifa, Fifth Harmony, Lana Del Rey, Norah Jones, James Arthur, One Republic, The Script, Stevie Wonder</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*EtNTSS3fVjDPi0HKAw3ANA.png" alt="Image" width="800" height="483" loading="lazy"></p>
<p><strong>Batch 5: Jason Mraz, John Legend, Pentatonix, Alicia Keys, Usher, Snoop Dogg, Macklemore, Zara Larsson, Jay-Z, Rihanna</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*i2DYW2eSNlKybqXOJRtntg.png" alt="Image" width="800" height="478" loading="lazy"></p>
<h4 id="heading-cluster-analysis"><strong>Cluster Analysis</strong></h4>
<p>Another way to find out the differences between these musicians in their musical repertoire is by grouping them in clusters. The general idea of a clustering algorithm is to divide a given dataset into multiple groups on the basis of similarity in the data.</p>
<p>In this case, musicians will be grouped in different clusters according to their music preferences. Rather than defining groups before looking at the data, clustering allows me to find and analyze the musician groupings that have formed organically.</p>
<p>Prior to clustering data, it is important to rescale the numeric variables of the dataset. Since I have mixed numerical data, where each audio feature is different from another and has different measurements, running the scale function (aka z-standardizing them) is a good practice to give equal weight to them. After that, I kept the musicians as the row names to be able to show them as labels in the plot.</p>
<pre><code>scaled.features &lt;- scale(mean_features[<span class="hljs-number">-1</span>])rownames(scaled.features) &lt;- mean_features$Musician
</code></pre><p>I applied the <strong>K-Means Clustering</strong> method, which is one of the most popular techniques of unsupervised statistical learning methods. It is used for unlabeled data. The algorithm finds groups in the data, with the number of groups represented by the variable <strong>K</strong>. The algorithm works iteratively to assign each data point to one of K groups based on the variables that are provided. Data points are clustered based on similarity.</p>
<p>In this instance, I chose <em>K = 6</em> — the clusters can be formed based on the six different genres I used when choosing the artists (Pop, Hip-Hop, R&amp;B, EDM, Rock, and Jazz).</p>
<p>After I applied the K-Means algorithm for each musician, I can plot a two-dimensional view of the data. In the first plot, the x-axis and y-axis correspond to the first and second principal components respectively. The eigenvectors (represented by red arrows) indicate the directional influence each variable has on the principal components.</p>
<p>Let’s have a look at the clusters that result from applying the K-Means algorithm to my dataset.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*T57D-wOsVH7Suc-FVEUi0Q.png" alt="Image" width="800" height="474" loading="lazy"></p>
<p>As you can see in the graph above, the x-axis is <strong>PC1 (30.24%)</strong> and the y-axis is <strong>PC2 (16.54%)</strong>. These are the first two principal components. The PCA graph shows that PC1 separates artists by loudness/energy vs acoustic/mellowness, while PC2 appears to separate artists on a scale of valence vs key, tempo and instrumentalness.</p>
<p>Because my data is multivariate, it is tedious to inspect all the many bivariate scatterplots. Instead, a single “summarizing” scatterplot is more convenient. The scatterplot of the first two principal components which were derived from the data has been shown in the graph. The percentage, likewise, is the variance explained by each component of the overall variability: the 1st component captured 30.24% and the 2nd component captured 16.54% of the information about the multivariate data.</p>
<p>If you’re interested to learn more about the math behind this algorithm, I recommend that you brush up on <a target="_blank" href="https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues">Principal Component Analysis</a>.</p>
<p>Let’s see which artists belong to which clusters:</p>
<pre><code>k_means$cluster
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*qQOP3E-4nHM9eVstkvGD9A.png" alt="Image" width="800" height="161" loading="lazy"></p>
<p>I have also plotted another radar chart containing the features for each cluster. It is useful to compare the attributes of the songs that each cluster creates.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*kAObmmSYnx8A5AOAmxTKMA.png" alt="Image" width="800" height="515" loading="lazy"></p>
<p><strong>Cluster 1</strong> contains four artists: Coldplay, Avicii, Marshmello, and Martin Garrix. Their music is mostly performed live and instrumental, usually loud and full of energy with high tempo. This is not too surprising, as three of the four artists perform EDM / House music, and Coldplay is known for their live concerts.</p>
<p><strong>Cluster 2</strong> contains 2 artists: Frank Sinatra and Norah Jones (any jazz fans out there?). Their music scores high on acousticness and the Major scale mode. However, they score low in all the remaining attributes. Typical Jazz tunes.</p>
<p><strong>Cluster 3</strong> contains ten artists: Post Malone, Kygo, The Chainsmokers, Adele, Lorde, Lana Del Rey, James Arthur, One Republic, John Legend, and Alicia Keys. This cluster scores average in mostly all the attributes. This suggests that this group of artists is well-balanced and versatile with style and creation, hence the diversity of genres presented in this cluster (EDM, Pop, R&amp;B).</p>
<p><strong>Cluster 4</strong> contains 15 artists: Ariana Grande, Maroon 5, Drake, Justin Bieber, Bruno Mars, Calvin Harris, Charlie Puth, Enrique Iglesias, Future, Wiz Khalifa, Fifth Harmony, Usher, Macklemore, Zara Larsson, and Rihanna. Their music is danceable, loud, high-tempo, and energetic. This group has the presence of many young mainstream artists in the Pop and Hip-Hop genres.</p>
<p><strong>Cluster 5</strong> contains 10 artists: Taylor Swift, Shawn Mendes, Ed Sheeran, Michael Buble, John Mayer, Elton John, The Script, Stevie Wonder, Jason Mraz, and Pentatonix. This is my favorite group! Taylor Swift? Ed Sheeran? John Mayer? Jason Mraz? Elton John? I guess I listen to a lot of singer-songwriter artists. Their music is mostly in the Major scale, while achieving perfect balance (average score) in all other attributes.</p>
<p><strong>Cluster 6</strong> contains nine artists: Kendrick Lamar, Kanye West, Eminem, Beyonce, Justin Timberlake, 50 Cent, Lil Wayne, Snoop Dogg, and Jay-Z. You already see the trend here: seven of them are Rappers, and even Beyonce and JT regularly collaborate with rappers. Their songs have high number of spoken words and speech-like sections, are long in duration, and often performed live. Any better description of rap music?</p>
<h4 id="heading-analysis-by-feature"><strong>Analysis by feature</strong></h4>
<p>The following charts show the values for each feature for every musician. The code below details the process for making the <strong>danceability</strong> diverging bar plot. The code for the other features has been omitted, but each feature’s plot is displayed subsequently.</p>
<p><strong>Danceability</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*mmdqIehzJaW53bsZz-r4aw.png" alt="Image" width="800" height="465" loading="lazy"></p>
<p>If you want to bust the moves and impress your crush, try listen to more of Future, Drake, Wiz Khalifa, Snoop Doog, and Eminem. On the other hand, don’t even attempt to dance to Frank Sinatra or Lana Del Rey’s tunes.</p>
<p><strong>Energy</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*nmymrRifwfiQinCuBd4YjQ.png" alt="Image" width="800" height="438" loading="lazy"></p>
<p>You’re a fairly energetic person if you listen to lots of Marhsmello, Calvin Harris, Enrique Iglesias, Martin Garrix, Eminem, Jay-Z. The opposite is true if you’re a fan of Frank Sinatra and Norah Jones.</p>
<p><strong>Loudness</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*CfGqLdEzbLosO_NXOoitiQ.png" alt="Image" width="800" height="438" loading="lazy"></p>
<p>The Loudness ranking is almost the same as the Energy one.</p>
<p><strong>Speechiness</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*0kD8rOdsUlasKAccun4ToA.png" alt="Image" width="800" height="431" loading="lazy"></p>
<p>All the Rap fans out there: what’s your favorite songs from Kendrick Lamar? or 50 Cent? or Jay-Z? Hmm, I’m surprised Eminem does not rank higher, as I personally think that he’s the GOAT of all rappers.</p>
<p><strong>Acousticness</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*ljkt02Nbop7eBctlHflmkQ.png" alt="Image" width="800" height="427" loading="lazy"></p>
<p>Acousticness is the exact opposite of Loudness and Energy. Mr. Sinatra and Mrs. Jones released some powerful acoustic tracks throughout their careers.</p>
<p><strong>Instrumentalness</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*YQ5rafbPvyNh-KanFWqNNg.png" alt="Image" width="800" height="424" loading="lazy"></p>
<p>EDM for the win! Martin Garrix, Avicii, and Marshmello produce tracks that contain almost no vocals.</p>
<p><strong>Liveness</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*DnYTLJ4GDEpwz4AYsh6OMw.png" alt="Image" width="800" height="429" loading="lazy"></p>
<p>So who are the 5 artists who performed the most live audio recordings? Jason Mraz, Coldplay, Martin Garrix, Kanye West, and Kendrick Lamar, in that order.</p>
<p><strong>Valence</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*OelJ9gnwDamJPvZxQFIBMg.png" alt="Image" width="800" height="428" loading="lazy"></p>
<p>Valence is the feature that describes musical positiveness conveyed by a track. Music by Bruno Mars, Stevie Wonder, and Enrique Iglesias are very positive, while music by Lana Del Rey, Coldplay, and Martin Garrix sound quite negative.</p>
<p><strong>Tempo</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sE4BMoJmy8msXXGNWxYYyg.png" alt="Image" width="800" height="428" loading="lazy"></p>
<p>Future, Marshmello, and Wiz Khalifa are kings of speed. They produce tracks with the highest tempo in beats per minute. And Snoop Dogg, lol? He tends to take some time to utter his magic words.</p>
<p><strong>Duration</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*4nZrGRrl94SrqjVLuu6l3g.png" alt="Image" width="800" height="429" loading="lazy"></p>
<p>Last but not least, songs by Justin Timberlake, followed by Elton John and Eminem, are, sometimes excruciatingly, long. In contrast, Frank Sinatra, Zara Larsson, and Pentatonix favor shorter music.</p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Whoa, I had a lot of fun doing this analysis and visualization project on Spotify data. Who could have thought that James Arthur and Post Malone are in the same cluster? Or Kendrick Lamar is the speediest rapper in the game? Or that Marshmello would beat Martin Garrix in producing energetic tracks?</p>
<p>Anyway, you can view the complete R Markdown, separate R code for processing and visualizing data, and the original dataset in <a target="_blank" href="https://github.com/khanhnamle1994/spotify-artists-analysis">my GitHub repository here</a>. From my own perspective, R is much better in data visualization than Python, with the likes of libraries such as <a target="_blank" href="https://www.statmethods.net/advgraphs/ggplot2.html">ggplot</a> and <a target="_blank" href="https://plot.ly/r/">plot.ly</a>. I highly encourage you to give R a try!</p>
<p>— —</p>
<p><em>If you enjoyed this piece, I’d love it if you hit the clap button</em> ? s<em>o others might stumble upon it. You can find my own code on</em> G<a target="_blank" href="https://github.com/khanhnamle1994"><em>itHub,</em></a> <em>and more of my writing and projects at</em> h<a target="_blank" href="https://jameskle.com"><em>ttps://jameskle.com/.</em></a> _You can also follow me on T<a target="_blank" href="https://twitter.com/@james_aka_yale">witter,</a> e<a target="_blank" href="mailto:khanhle.1013@gmail.com">mail me directly</a> or f<a target="_blank" href="http://www.linkedin.com/in/khanhnamle94">ind me on LinkedIn.</a> S<a target="_blank" href="http://eepurl.com/deWjzb">ign up for my newsletter</a> to receive my latest thoughts on data science, machine learning, and artificial intelligence right at your inbox!_</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
