Open abhishekgoyal-a11y opened 2 weeks ago
THESE ENDPOINTS WILL WORK WITH BELOW ACCESS TOKEN GENERATED.
we need the token of all scopes - https://developer.spotify.com/documentation/web-api/concepts/scopes
PYTHOCODE
import webbrowser import requests from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys import urllib.parse import time import requests import json import base64 import urllib.parse from http.server import BaseHTTPRequestHandler, HTTPServer #
CLIENT_ID = '95e38f735fed4b2086167f8b8ef82fd6' CLIENT_SECRET = '89aac6b76adf4bd8bf0e241f34eac0f3' REDIRECT_URI = 'https://example.org/callback'
AUTH_URL = 'https://accounts.spotify.com/authorize' TOKEN_URL = 'https://accounts.spotify.com/api/token'
SCOPES = 'user-library-modify'
def get_authorization_url(): params = { 'client_id': CLIENT_ID, 'response_type': 'code', 'redirect_uri': REDIRECT_URI, 'scope': SCOPES, }
auth_url = f"{AUTH_URL}?{urllib.parse.urlencode(params)}"
return auth_url
def get_access_token(code): headers = { 'Authorization': 'Basic ' + base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode('ascii') }
data = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
}
response = requests.post(TOKEN_URL, headers=headers, data=data)
if response.status_code == 200:
token_info = response.json()
return token_info['access_token'], token_info['refresh_token']
else:
print("Error getting access token")
return None, None
def get_user_profile(access_token): url = 'https://api.spotify.com/v1/me' headers = { 'Authorization': f'Bearer {access_token}', } response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
print("Error getting user profile")
return None
class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): print("Started")
if 'code=' in self.path:
code = self.path.split('code=')[1]
print(f"Authorization code: {code}")
# Step 5: Get the access token using the code
access_token, refresh_token = get_access_token(code)
if access_token:
# Step 6: Use the access token to get user profile
user_profile = get_user_profile(access_token)
if user_profile:
self.send_response(200)
self.end_headers()
self.wfile.write(f"User profile: {user_profile}".encode())
else:
self.send_response(500)
self.end_headers()
self.wfile.write("Failed to get user profile".encode())
else:
self.send_response(500)
self.end_headers()
self.wfile.write("Failed to get access token".encode())
else:
self.send_response(400)
self.end_headers()
self.wfile.write("Error: Authorization code not found in URL".encode())
def run_server():
server = HTTPServer(('localhost', 8888), RequestHandler)
print('Listening for redirect on http://localhost:8888/callback')
# server.handle_request()
def get_access_token1(code): headers = { 'Authorization': 'Basic ' + base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode('ascii') }
data = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
}
response = requests.post('https://accounts.spotify.com/api/token', headers=headers, data=data)
if response.status_code == 200:
token_info = response.json()
return token_info['access_token'], token_info['refresh_token']
else:
print("Error getting access token", response.text)
return None, None
def fetch_authorization_code():
options = Options()
options.add_argument("--headless") # Run in headless mode if you don't want to see the browser
# Open the browser
driver = webdriver.Chrome(options=options)
driver.get(auth_url)
try:
# Wait for the login form to appear
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "login-username"))
)
# Enter username
username = driver.find_element(By.ID, "login-username")
username.send_keys("kumar.abhishekgoyal@gmail.com")
# Enter password
password = driver.find_element(By.ID, "login-password")
password.send_keys("-:qtW(Df2njx@kf")
# Click the login button
login_button = driver.find_element(By.ID, "login-button")
login_button.click()
# Wait for redirect to callback URL and fetch the authorization code
WebDriverWait(driver, 10).until(
lambda d: REDIRECT_URI in d.current_url
)
# Extract the authorization code from the redirected URL
current_url = driver.current_url
print(current_url)
authorization_code = urllib.parse.parse_qs(urllib.parse.urlparse(current_url).query).get('code')[0]
print("Authorization Code:", authorization_code)
return authorization_code
except Exception as e:
print("An error occurred:", e)
return None
finally:
driver.quit()
auth_url = get_authorization_url()
authorization_code = fetch_authorization_code()
run_server() # Start a simple HTTP server to handle the redirect
a,e = get_access_token1(authorization_code)
print(a) print(e)
headers = { "Authorization": f"Bearer {a}", "Content-Type": "application/json" }
url = 'https://api.spotify.com/v1/me/albums?ids=4aawyAB9vmqN3uQ7FjRGTy'
data = { "ids": ["string"] # Replace with the actual IDs you want to send }
response = requests.put(url, headers=headers, data=json.dumps(data))
if response.status_code == 200: print(response.text) # Print the response if successful else: print(f"Error {response.status_code}: {response.text}")