abhishekgoyal-a11y / SpotifyAPIAutomation

0 stars 0 forks source link

Automate # Remaining Album Endpoints #2

Open abhishekgoyal-a11y opened 2 weeks ago

abhishekgoyal-a11y commented 2 weeks ago
abhishekgoyal-a11y commented 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 #

Your Spotify app credentials

CLIENT_ID = '95e38f735fed4b2086167f8b8ef82fd6' CLIENT_SECRET = '89aac6b76adf4bd8bf0e241f34eac0f3' REDIRECT_URI = 'https://example.org/callback'

Spotify's authorization endpoint

AUTH_URL = 'https://accounts.spotify.com/authorize' TOKEN_URL = 'https://accounts.spotify.com/api/token'

Define the scopes you're requesting

SCOPES = 'user-library-modify'

Step 1: Direct the user to Spotify for authorization

def get_authorization_url(): params = { 'client_id': CLIENT_ID, 'response_type': 'code', 'redirect_uri': REDIRECT_URI, 'scope': SCOPES, }

URL encode the parameters

auth_url = f"{AUTH_URL}?{urllib.parse.urlencode(params)}"
return auth_url

Step 2: Get the access token

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

Step 3: Use the access token to make an API request

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

Step 4: Simple HTTP server to handle the redirect and extract the code

class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): print("Started")

Extract the authorization code from the URL

    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():

Start the server to listen for the redirect

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

Automated browser interaction using Selenium

def fetch_authorization_code():

Set up the Chrome WebDriver

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()

Step 1: Get the authorization URL

auth_url = get_authorization_url()

Fetch the authorization code

authorization_code = fetch_authorization_code()

webbrowser.open(auth_url) # Open the URL in the browser for user login

run_server() # Start a simple HTTP server to handle the redirect

code = input("code")

a,e = get_access_token1(authorization_code)

print(a) print(e)

headers = { "Authorization": f"Bearer {a}", "Content-Type": "application/json" }

Set the URL and headers for the API request

url = 'https://api.spotify.com/v1/me/albums?ids=4aawyAB9vmqN3uQ7FjRGTy'

Data to be sent in the request

data = { "ids": ["string"] # Replace with the actual IDs you want to send }

response = requests.put(url, headers=headers, data=json.dumps(data))

Check if the request was successful

if response.status_code == 200: print(response.text) # Print the response if successful else: print(f"Error {response.status_code}: {response.text}")