File size: 1,829 Bytes
51245ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import requests
import base64
import json
import os
import sys

client_id = os.environ["CLIENT_ID"]
client_secret= os.environ["CLIENT_SECRET"]

def get_playlist_track_uris(playlist_id):
    access_token = get_access_token(client_id, client_secret)

    playlist_data = get_playlist_data(access_token, playlist_id)

    # Output the playlist data to a file
    # with open('playlist-tracks.json', 'w') as outfile:
        # json.dump(json.loads(playlist_response.text), outfile)

    track_uris = [item['track']['uri'] for item in playlist_data['tracks']['items']]
    print(track_uris)

    # Output the track uris into a file
    # with open('track-uris-new.txt', 'w') as output_file:
    #     output_file.write('\n'.join(track_uris))

    return track_uris
    


def get_access_token(client_id, client_secret) -> str: 
    base64_string = base64.b64encode((client_id + ':' + client_secret).encode('ascii')).decode('ascii')

    auth_headers = {
            'Authorization': 'Basic ' + base64_string,
            'Content-type': 'application/x-www-form-urlencoded'
    }
    auth_data = {'grant_type': 'client_credentials'}

    auth_response = requests.post('https://accounts.spotify.com/api/token', headers=auth_headers, json=True, data=auth_data)
    access_token = json.loads(auth_response.text)['access_token']

    return access_token

def get_playlist_data(access_token, playlist_id):
    get_playlist_headers = {
        'Authorization': 'Bearer ' + access_token,
        'Content-Type': 'application/json',
    }

    playlist_response = requests.get('https://api.spotify.com/v1/playlists/' + playlist_id, headers=get_playlist_headers)
    playlist_data = json.loads(playlist_response.text)

    return playlist_data

if __name__ == "__main__":
    playlist_id = sys.argv[1]

    get_playlist_track_uris(playlist_id)