No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Obteniendo la discografía

23/30
Recursos

Aportes 34

Preguntas 2

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Funcion para obtener el JSON del albúm

def get_album_json(album_id):
    header = {"Authorization": "Bearer {}".format(token)}
    url_base = 'https://api.spotify.com/v1'
    album = requests.get(url_base+'/albums/'+album_id, headers=header)
    if album.status_code == 200: 
        return album.json()
    else:
        print(f"Fail in request. HTTP error: {album.status_code}")

Función para obtener los IDS del Album de un artista:

def get_albums_ids(items):
    albums_ids = []
    for i in range(len(items)):
        album_id = items[i]['id']
        albums_ids.append(album_id)
    return albums_ids

Donde items son los items que vimos en esta clase, y que yo transforme en una función:

items = get_artists_albums_json(url_base,ep_artist,id_im)['items']

def get_artists_albums_json(url_base, ep_artist, artist_id):
    header = {"Authorization": "Bearer {}".format(token)}
    params = {'country': 'AR'}
    albums = requests.get(url_base+ep_artist.format(artist_id=id_im)+'/albums', headers=header, params=params)
    
    if albums.status_code == 200:
        return albums.json()
    else:
        print(f"Fail in request. HTTP error: {albums.status_code}")

Creo que ahora mi numero favorito es 200

Mi solucion al reto 🚀

def get_album_info(id_album,token, country = 'AR'):
    url_base = 'https://api.spotify.com/v1'
    ep_album = '/albums/{id_album}'.format(id_album=id_album)
    header = {'Authorization': 'Bearer {}'.format(token)}
    params = {'country':country}
    info_album = requests.get(url_base+ep_album,
									headers=header,
									params=params)
    return info_album.json()

Mi pequeño codigo:

def get_album_info():
    token = get_token(cliente_id,cliente_secret)
    header = {'Authorization':"Bearer " + token}
    ep_albums = url_api_artist + "/albums"
    albums_r = requests.get(ep_albums, headers= header)
    id_albums = [albums_r.json()['items'][i]['id'] for i in range(len((albums_r.json()['items'])))]
    dicter = {}
    counter = 0
    for id_album in id_albums:
        counter += 1
        ep_albums_id = "https://api.spotify.com/v1/albums/" + id_album
        albums_id_r = requests.get(ep_albums_id, headers= header)
        print(albums_id_r.status_code)
        dicter[counter] = albums_id_r.json()['release_date']
    return dicter
get_album_info()

Función para obtener los albums:

# Obtención de albums
# Entrega el resultado del request
def get_albums(artist_id):
    url_base = 'https://api.spotify.com/v1/artists/'
    header = {'Authorization': 'Bearer {}'.format(token)}
    # endpoint de los albums
    ep_albums = '{artist_id}/albums'
    url_base + ep_albums
    params = {'country': 'CO'}
    
    try:
        albums_artist = requests.get(url_base+ep_albums.format(artist_id=id_metallica), headers=header, params=params)
        if albums_artist.status_code == 200:
            return albums_artist
        else:
            print(f'HTTP error: {albums_artist.status_code}')
    except Exception as e:
        print('Error: ', e)

Función para obtener el id de los albums:

# Entrega una lista con el id de los albums
def get_id_albums(albums_request):
    id_albums = []
    try:
        albums = len(albums_request.json()['items'])
        for album in range(albums):
            id_albums.append(albums_request.json()['items'][album]['id'])
        return id_albums
    except Exception as e:
        print('Error: ', e)

Función para obtener la información de un album:

def get_info_album(id_album):
    url_base = 'https://api.spotify.com/v1/albums/'
    ep_album = '{album_id}' 
    params = {'country': 'CO'}
    
    # uso de la función para obtener un token válido
    #token = get_token(client_id, client_secret) 
    header = {'Authorization': 'Bearer {}'.format(token)}
    
    try:
        album_artist = requests.get(url_base+ep_album.format(album_id=id_album), headers=header, params=params)
        if album_artist.status_code == 200:
            return album_artist
        else:
            print(f'HTTP error: {album_artist.status_code}')
    except Exception as e:
        print('Error: ', e)

Mi solución al reto con decoradores

def buscar(func):
    def inner_func(name):
        url_busqueda = 'https://api.spotify.com/v1/search'
        header = {'Authorization': 'Bearer {}'.format(token)}
        params = {'q':f'{name}'.replace(' ', '+'), 'type':'album', 'market':'US'}
        busqueda = requests.get(url_busqueda, headers=header, params=params)
        if busqueda.status_code != 200:
            print('Error... No he encontrado ese artista...')
            return None
        else:
            print('Hecho!')
            return func(busqueda.json()['albums']['items'][0]['id'])
    return inner_func
        
@buscar
def buscar_album(name):
    url_album = 'https://api.spotify.com/v1/albums/{album_id}'.format(album_id=name)
    print(url_album)

    header = {'Authorization': 'Bearer {}'.format(token)}
    album = requests.get(url=url_album, headers=header)
    return album.json()


pprint(buscar_album('21'))

hola.

Reto
Aporte para tener id, name, release_date y total tracks en un data frame.

dic_songs = [(album['id'], album['name'],album['release_date'],album['total_tracks']) for album in albums_im.json()['items']]
pd_songs = pd.DataFrame(dic_songs, columns=['id','name','date','tracks'])
pd_songs

Reto

Mi aporte para obtener el id y nombre de cada album

# reto
# obtener información de cada album de un artista
for album in album_list:
    album_id = album['id']
    album_name = album['name']
    album_dict = {'id': album_id, 'nombre': album_name}
    print(album_dict)

Mi solución al reto.

def get_albums_per_artist(artist_id, token, **kwargs):
    rkwargs = {'url': base_url + ep_albums.format(artist_id=artist_id)}
    if not kwargs:
        rkwargs['headers'] = {'Authorization': 'Bearer {}'.format(token)}
        rkwargs['params'] = {'Country': 'PE'}
    r = requests.get(**rkwargs, **kwargs)
    if r.status_code != 200:
        print('Error en la request', r.json())
        return None
    return r.json()['items']

solución al reto:

def get_info_album_list(album_list, token):
    url_base = 'https://api.spotify.com/v1'
    ep_album_info = '/albums/{album_id}'
    header = {'Authorization':'Bearer {}'.format(token)}
    params = {'country':'AR'}
    
    lista = []    
    for album in album_list:
        album_info = requests.get(url_base + ep_album_info.format(album_id = album[0]), headers=header, params=params )
        if album_info.status_code == 200:
            added = album_info.json()
            lista.append(added)
        else:
            print(f"HTTP error: {album_info.status_code}")
    return lista    
lista_albums = [(album['id'], album['name'], album['release_date'], album['total_tracks']) for album in albums_im.json()['items']]
lista_albums

Resolución del reto

¡Reto Completado! 💪🏼

def get_album_info(album_id, token):
    """Función que devuelve un objeto JSON con la información de un 
    álbum en específico"""

    header = {'Authorization': 'Bearer {}'.format(token)}
    paramas = {'country': 'AR'}
    album = requests.get(url_base + 				 
    ep_album.format(album_id=album_id), headers=header, 
    params=params)
    return album.json()

Solucion

def get_album_info(token, artist_id, url_base):
    header = {'Authorization': 'Bearer {}'.format(token)}
    ep_albums = '/artists/{artist_id}/albums'
    url_albums = url_base + ep_albums.format(artist_id = artist_id)
    params = {'country':'CO'}
    albums = requests.get(url_albums, headers=header, params=params)

    if albums.status_code != 200:
        print(f"Fail in request. HTTP error: {albums.status_code}")   
    else:
        return albums.json()

solucion
`

def get_album(id_album, token): 
    header = {'Authorization': 'Bearer {}'.format(token)}
    params ={'country':'CR'}
    album = requests.get(url_base+ep_album.format(id_album=id_album), headers=header, params=params)
    return album.json()

`

Reto OK,

def get_info_album(id_album, id_token):
    header = { 'Authorization': 'Bearer {}'.format(token)}
    ep_album = '/albums/{album_id}'
    print(url_base+ep_album)
    info_album=requests.get(url_base+ep_album.format(album_id=id_album), headers=header, params=params)
    return info_album

jeeeeee

def get_token(client_id, client_secret):
    """
    Función que extrae un JSON con la información de un album identificado con id
    """
    encoded = base64.b64encode(bytes(client_id+':'+client_secret, 'utf-8'))
    params = {'grant_type' : 'client_credentials'}
    header = {'Authorization' : 'Basic ' + str(encoded, 'utf-8')}
    r = requests.post('https://accounts.spotify.com/api/token', headers=header, data=params)
    if r.status_code != 200:
        print('Error en la request', r.json())
        
        return None
    else:
        print(f'Token válido por {r.json()["expires_in"]} segundos')
        return r.json()['access_token']```

Les dejo mi implementacion

def get_album_info(album_id):
  endpoint_album = '/albums/{album_id}'
  headers = {'Authorization': 'Bearer {}'.format(token)}
  params = {'country': 'MX'}
  return album_data.append((requests.get(url_base+endpoint_album.format(album_id=album['id']), headers= headers, params=params)).json())
album_data = []
for album in albums:
  album_data.append(get_album_info(album['id']))
  print(album['id'])

Aquí esta el reto:

def albums(token,id_im):
    import pandas as pd
    ep_albums =f'/artists/{id_im}/albums'
    header = {'Authorization': f'Bearer {token}'}
    params = {'country':'CO'}
    albums_im = requests.get(url_base+ep_albums, headers=header, params=params)
    if r.status_code != 200:
        print('Error en la request.', r.json())
        return None
    print(f"válido")
    return pd.DataFrame(albums_im.json()['items'])

La función regresa un DataFrame con la información de lso albums.

Reto 😄

def albums_informations(client_id,client_secret ,album_id):
   
    token = get_token(client_id,client_secret)
    header = {'Authorization':'Bearer {}'.format(token)}
    ep_albums = '/albums/{album_id}'
    url_base = 'https://api.spotify.com/v1'
    url = url_base + ep_albums
    params = {'country':'AR'}
    albums=  requests.get(url.format(album_id = album_id),headers=header, params =params)
    return albums.json()

Realicé dos funciones, que juntas permiten obtener datos de los álbumes de un artista ingresando su nombre:

def get_id():
    url_busqueda = 'https://api.spotify.com/v1/search'
    search_params = {'q':'', 'type':'artist', 'market':'AR'}
    global header
    artista = input('Que artista buscas? ').replace(' ', '+')
    search_params['q'] = artista
    busqueda = requests.get(url_busqueda, headers=header, params=search_params)
    if busqueda.status_code == 200:
        df = pd.DataFrame(busqueda.json()['artists']['items'])
        id = df.sort_values(by='popularity', ascending=False).iloc[0]['id']
        return id
    else:
        print('No se pudo obtener el id')
        return None
    
def get_albums():
    artist_id = get_id()
    ep_albums = '/artists/{artist_id}/albums'
    global url_base
    global header
    params = {'country' : 'AR'}
    url = url_base + ep_albums.format(artist_id=artist_id)
    albums = requests.get(url, headers=header, params=params)
    if albums.status_code == 200:
        albumes = pd.DataFrame(albums.json()['items'])
        return albumes[['id', 'name', 'album_type', 'release_date']]
    else:
        print('No se pudieron obtener los albumes')
        return None
        

Mi solución:

Codigo del reto:

def obtener_info_album(token, id_album):
    header = {'Authorization': 'Bearer {}'.format(token)}
    params = {'country':'CO'}
    ep_album = 'https://api.spotify.com/v1/albums/{id_album}'
    album = requests.get(ep_album.format(id_album=id_album), headers=header, params=params)
    if album.status_code != 200:
        print('Error en la request.', album.json())
        return None
    return album.json()

Solución al reto:

Hola que tal mi solucion al reto del profe, como me ha gustado el curso y lo facil que explica como usar una API.Agradezco que Spotify tiene muy bien documentada la de ellos.

def get_info_album(album_id, token):
    ''' Get info album '''
    url = 'https://api.spotify.com/v1/albums/{}'.format(album_id)

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0',
        'Authorization': 'Bearer {}'.format(token),
    }

    response = requests.get(url, headers=headers)
    print(response.json())

    return response.json()

Reto:

# obtener id
df = pd.DataFrame(albums_im.json()['items'])

# First album of Iron Maden
fs_album_id = df.sort_values(by='release_date', ascending=False).iloc[0]['id']

# end point de datos del album 
ep_data_album = '/albums/{album_id}'

# Tracks of album
header ={'Authorization': f'Bearer {token}'}
params = {'country': 'AR'}
album_tracks_im = requests.get(url_base+ep_data_album.format(album_id=fs_album_id), 			headers=header, params=params)
album_tracks_im.json()

varié mi solución para que la consulta me devuelva ciertas variables del albúm, no todo el json. espero les sirva ñ.ñ

def get_album_info(artist_id):
    '''
    función que devuelve la información del álbum del artista 
    (nombre del álbum, fecha de lanzamiento y cantidad de canciones)
    pasandole el id del mismo.
    '''
    
    ep_albums = '/artists/{artist_id}/albums'
    url_base = 'https://api.spotify.com/v1'
    params = {'country':'CO'}
    album = requests.get(url_base+ep_albums.format(artist_id=artist_id), headers=header, params=params)
    if album.status_code != 200:
        print("Error en la request.", album.json())
        return None
    print('ID Válido.')
    df = pd.DataFrame(album.json()['items'])
    return print('Nombre del álbum:',df.iloc[0]['name'],'\n',
                 'Fecha de lanzamiento:',df.iloc[0]['release_date'],'\n',
                 'Total de canciones:',df.iloc[0]['total_tracks']) 

Output de get_album_info(id_artista): #usé a The Killers como ejemplo💙.


ID Válido.
Nombre del álbum: Imploding The Mirage 
 Fecha de lanzamiento: 2020-08-21 
 Total de canciones: 10

He luchado un poco porque había listas y diccionarios
Espero que no me toque ahora rehacer el código

def get_albums_artist (artist_id):
  """Función recibe el id de un artista en formato str
      devuelve los albums de ese artista"""

  # Defifiendo rutas de URL
  url_base = 'https://api.spotify.com/v1'
  ed_albums = '/artists/{id_artist}/albums'
  url_albums_artist = url_base+ed_albums.format(id_artist = artist_id)

  # Parámetros 
  header = {'Authorization' : 'Bearer {}'.format(token)}
  params = {'country' : 'CO'}

  # Búsqueda albums del artista
  r = requests.get(url_albums_artist, headers=header, params=params)

  if r.status_code == 200:

    # inicializamos variables
    albums_content = r.json()['items']
    albums = []

    # Recorremos la lista buscando los id y name
    for album in albums_content:
      album = (album['id'], album['name'])
      albums.append(album)

    # Retorna una lista con ('id', 'name')
    return albums
    
  else:
    print('Error obteniendo los albums de id_artista {}'.format(id_artist))

interesante el reto

Hola. Comparto mi código con la solución al reto.

  1. El usuario escribe el artista que quiere scrapear
  2. El usuario puede escoger si desea ver una lista con los artistas que su nombre es similar al que escribió, ordenados ascendentemente según su popularidad
  3. El programa muestra los álbumes del artista más popular
import requests
import pandas as pd
import base64

def main(user_artist):
    client_id = 'your Client ID '
    client_secrect = 'your client secrect id'

    artist(get_token(client_id,client_secrect),user_artist)

def get_token(client_id,client_secrect):
    encoded = base64.b64encode(bytes(client_id+':'+client_secrect, 'utf-8'))
    params = {'grant_type':'client_credentials'}
    header = {'Authorization':'Basic '+ str(encoded, 'utf-8')}
    r = requests.post('https://accounts.spotify.com/api/token', headers=header, data=params)
    if r.status_code != 200:
        print('Request error.', r.json())
        return None
    print('Valid token by {} seconds'. format(r.json()['expires_in']))
    token = r.json()['access_token']

    return token

def artist(token,user_artist):
    search_url = 'https://api.spotify.com/v1/search'
    search_params = {'q': user_artist , 'type' : 'artist', 'market' : 'CO'}
    header = {'Authorization' : 'Bearer {}'.format(token)}
    search = requests.get(search_url, headers=header, params=search_params)
    if search.status_code != 200:
        print('Request artist error', search.json())
        return None

    df_artist = pd.DataFrame(search.json()['artists']['items'])
    artist_id = df_artist.iloc[0]['id']
    
    artists_id = []
    for i in range(len(df_artist['id'])):
        artists_id.append(df_artist.iloc[i]['id'])

    artist_popularity = df_artist.sort_values(by='popularity', ascending=False).loc[0:,'name':'popularity']
    view_artist = input(str('Show all artist?  y/n   '))
    if view_artist == 'y':
        print(artist_popularity)
    else:
        pass

    album(token,artist_id)

def album(token,artist_id):
    header = {"Authorization": "Bearer {}".format(token)}
    url_base = 'https://api.spotify.com/v1'
    ep_albums = '/artists/{artist_nid}/albums'
    params = {'country':'CO'}
    
    albums = []
    albums_artist = requests.get(url_base + ep_albums.format(artist_nid=artist_id), headers=header, params=params)
    if albums_artist.status_code == 200:
        df_albums = pd.DataFrame(albums_artist.json())
        for i in range(len(df_albums)):
            name = df_albums.loc[i,'items'].get('name')
            albums.append(name)
        
        print(albums)
        
    else:
        print(f"Fail in request. HTTP error: {albums_artist.status_code}{albums_artist.json()}")

if __name__ == "__main__":
    print('Welcome to Spotify Scraper')
    user = input(str('Choose an artist to scrape:\n - '))
    user_artist = user.replace(' ','+')
    main(user_artist)```

MI solucion al reto:

Tres funciones, la primera para obtener el id de los albumes

def albums_id(items):
    discografia=[]
    for i in range(len(items)):
        album_id=items[i]['id']
        discografia.append(album_id)
    return discografia

La segunda, para obtener el endopoint de los albumes

<def get_endpoint(discos):
    discos=albums_id(items)
    ep_discografia = '/albums/{id}'
    url_discografia =url_base+ep_discografia
    albumes=[]
    for disco in discos:
        header = {'Authorization':'Bearer {}'.format(token)}
        params = {'country': 'CO'}
        d=ep_discografia.format(id=disco)
        discografia_hu = requests.get(url_base+ep_discografia.format(id=disco), headers=header, params=params)
        albumes.append(d)
    return albumes>

Y finalmente, la tercera funcion para obtener la discografia

<def get_discography(albumes):
    albumes
    discografia = []
    for i in range(len(albumes)):
        disco_params = {'available_markets': 'CO'}
        header = {'Authorization':'Bearer {}'.format(token)}
        url_albumes=url_base+albumes[i]
        albumes_hu = requests.get(url_albumes, headers=header, params=disco_params)
        discography=discografia.append(albumes_hu.json()['name'])
    print(f'Total de albumes al dia de hoy: {len(discografia)}\nTitulo de los albumes: \n{discografia}')
    return discografia>