DEV Community

Thirumoorthy S
Thirumoorthy S

Posted on

Add Spotify API to fetch current playing song in your react app

  1. Create an Application in Spotify Developer.
  2. Authorize your site.
  3. Get Refresh token
  4. Integrate the API.

Create an Application in Spotify Developer

  • Open Spotify Developer and login to your Spotify account.
  • Click Create app and enter your App name and Description and redirect uri (eg : http://localhost:3000). If it asking for secured and valid uri, convert your local app into https and instead of 'localhost' give your IP address and check 'WebAPI'.
  • Click 'Save' button.

Authorize your site

  • Go to Postman or any API Platform
  • Set method as 'GET' and api call as
https://accounts.spotify.com/authorize
Enter fullscreen mode Exit fullscreen mode

Then add query params

query params

  • Copy your API as
https://accounts.spotify.com/authorize?client_id=<your_client_id>&response_type=code&redirect_uri=https://<your_ip>:3000&scope=user-read-currently-playing
Enter fullscreen mode Exit fullscreen mode
  • Go to your browser and run the above api call, after authorization you can get your 'code' in url as
https://<your_redirect_uri>/?code=<code>
Enter fullscreen mode Exit fullscreen mode

Base64 of client_id:client_secret

  • Run this to get your basic authorization code.
const basic = Buffer.from(`${client_id}:${client_secret}`).toString("base64");
Enter fullscreen mode Exit fullscreen mode

Get Refresh token

  • In Postman, create new API call and set method as 'POST' and give api call as
https://accounts.spotify.com/api/token
Enter fullscreen mode Exit fullscreen mode
  • Set Headers as headers
  • Set Body-> x-www-form-urlencoded as

body

  • Run your Post api call and get your "Refresh token".[ Note : you may get access token here, but it is temporary, instead follow the next step ].

Integrate the API

  • to get access token
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;
const refresh_token = <your_refresh_token>;

const getAccessToken = async () => {
  const basic = Buffer.from(`${client_id}:${client_secret}`).toString("base64");
  const response = await fetch(TOKEN_ENDPOINT, {
    method: "POST",
    headers: {
      Authorization: `Basic ${basic}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: queryString.stringify({
      grant_type: "refresh_token",
      refresh_token,
    }),
  });
  return response.json();
};

Enter fullscreen mode Exit fullscreen mode
  • To get the data of your current playing song,
const [spotifyMsg, setSpotifyMsg] = useState('');
const [songUrl, setSongUrl] = useState('');
const [albumImageUrl, setAlbumImageUrl] = useState('');
const [isPlaying, setIsPlaying] = useState(false);
useEffect(() => {

        const fetchSpotifyData = async () => {
            try {
                const { access_token } = await getAccessToken();
                const response = await axios.get('https://api.spotify.com/v1/me/player/currently-playing', {
                    headers: {
                        'Authorization': `Bearer ${access_token}`,
                    }
                });
                if (response.data) {
                    const songName = response.data.item.name;
                    const artistName = response.data.item.artists.map(artist => artist.name).join(', ');
                    setAlbumImageUrl(response.data.item.album.images[0].url);
                    setSongUrl(response.data.item.external_urls.spotify);
                    setIsPlaying(response.data.is_playing);

                    setSpotifyMsg(`${songName} by ${artistName}`);
                }
            } catch (error) {
                console.error('Error fetching Spotify data:', error);
            }
        };
        fetchSpotifyData();
    }, []);
Enter fullscreen mode Exit fullscreen mode
  • Render those data into your FE wherever you need๐Ÿ˜๐Ÿ˜๐Ÿ˜.

Thanks and good luck!!!

Top comments (1)

Collapse
 
uday_k_e3a7108774e1792288 profile image
Uday K

Very helpful , Thank you