clxrityy / next-spotify-stats

Fetch information and statistics about any Spotify artist

Home Page:https://next-spotify-stats.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use Python to connect to Spotify's API

from dotenv import load_dotenv
import os

load_dotenv()
client_id = os.getenv('SPOTIFY_CLIENT_ID')
client_secret = os.getenv('SPOTIFY_CLIENT_SECRET')
  • Define a function to generate your authentication token & headers.
    • See Spotify's Web API Documentation for more information on how this works.
    • Send a POST request to the token endpoint URI. ("https://accounts.spotify.com/api/token")
import base64
from requests import post
import json

def get_token():
    auth_string = f"{client_id}:{client_secret}"
    auth_bytes = auth_string.encode('utf-8')
    auth_base64 = str(base64.b64.encode(auth_bytes), 'utf-8')

    url = "https://accounts.spotify.com/api/token"
    headers = {
        "Authorization": "Basic " + auth_base64,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {
        "grant-type": "client_credentials"
    }

    result = post(url=url, headers=headers, data=data)
    json_result = json.loads(result.content)
    token = json_result['access_token']

    return token

def get_auth_header(token):
    return {
        "Authorization": "Bearer " + token
    }

Create API routes with Flask

pip install flask
from flask import Flask

app = Flask(__name__)

if __name__ == "__main__":
    app.run(load_dotenv=True)

Example route

# http://127.0.0.1:5328/api/python
@app.route("/api/python")
def hello_world():
    return f"<h1>Hello World</h1>"

Display data on the front end

  • Create an example route to fetch an example piece of data, such as your access token.
token = get_token()

@app.route("/api/token")
def tokenRoute():
    return token
  • Now fetch the data in a client component.

/components/Token.tsx

'use client';
import React, { useCallback } from 'react';

const Token = async () => {

    async function getData() {
        const res = await fetch('http://127.0.0.1:5328/api/token');

        if (!res.ok) {
            throw new Error("Failed to fetch data")
        }
        return res.json();
    }

    const data = await getData();

    return (
        <p>
            {data}
        </p>
    )

}

Template repository from Vercel

View vercel's nextjs-flask template here.

npx create-next-app nextjs-flask --example "https://github.com/vercel/examples/tree/main/python/nextjs-flask"

The Flask server will be running on http://127.0.0.1:5328 – feel free to change the port in package.json (you'll also need to update it in next.config.js).

About

Fetch information and statistics about any Spotify artist

https://next-spotify-stats.vercel.app


Languages

Language:TypeScript 61.4%Language:Python 14.9%Language:JavaScript 13.5%Language:CSS 10.2%