diff --git a/Lab_APIS.ipynb b/Lab_APIS.ipynb new file mode 100644 index 0000000..79ad1c2 --- /dev/null +++ b/Lab_APIS.ipynb @@ -0,0 +1,542 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + } + }, + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "id": "f4itcq1ibxAH" + }, + "outputs": [], + "source": [ + "import requests\n", + "\n", + "\n", + "username = \"torvalds\"" + ] + }, + { + "cell_type": "code", + "source": [ + "# Construir la URL del endpoint de usuario\n", + "user_url = f\"https://api.github.com/users/{username}\"\n", + "\n", + "# Hacer la solicitud GET a la API de GitHub para obtener datos del perfil\n", + "response = requests.get(user_url)\n", + "\n", + "# Verificar si la solicitud fue exitosa (código 200)\n", + "if response.status_code != 200:\n", + " print(f\"Error al obtener datos del usuario: {response.status_code}\")\n", + "else:\n", + " user_data = response.json() # Convertir la respuesta JSON a un diccionario de Python\n", + "\n", + " # Extraer campos importantes del perfil\n", + " name = user_data.get(\"name\")\n", + " login = user_data.get(\"login\") # nombre de usuario (debería ser igual a username)\n", + " bio = user_data.get(\"bio\")\n", + " public_repos = user_data.get(\"public_repos\")\n", + " followers = user_data.get(\"followers\")\n", + " following = user_data.get(\"following\")\n", + " location = user_data.get(\"location\")\n", + " profile_url = user_data.get(\"html_url\")\n", + "\n", + " # Imprimir datos de perfil (formato básico, refinaremos formato más adelante)\n", + " print(\"GitHub Profile:\", login)\n", + " print(\"Name:\", name)\n", + " print(\"Username:\", login)\n", + " print(\"Bio:\", bio)\n", + " print(\"Public Repos:\", public_repos)\n", + " print(\"Followers:\", followers)\n", + " print(\"Following:\", following)\n", + " print(\"Location:\", location)\n", + " print(\"Profile URL:\", profile_url)\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "biFLzheGb323", + "outputId": "a97aff02-e22b-43b1-cead-8a65d1edf6a8" + }, + "execution_count": 2, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "GitHub Profile: torvalds\n", + "Name: Linus Torvalds\n", + "Username: torvalds\n", + "Bio: None\n", + "Public Repos: 8\n", + "Followers: 243336\n", + "Following: 0\n", + "Location: Portland, OR\n", + "Profile URL: https://github.com/torvalds\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "# Construir la URL para obtener repositorios, solicitando hasta 100 repos por página\n", + "repos_url = f\"https://api.github.com/users/{username}/repos?per_page=100\"\n", + "\n", + "# Hacer la solicitud GET para obtener la lista de repositorios\n", + "response_repos = requests.get(repos_url)\n", + "\n", + "if response_repos.status_code != 200:\n", + " print(f\"Error al obtener repositorios: {response_repos.status_code}\")\n", + "else:\n", + " repos_data = response_repos.json() # lista de diccionarios, cada uno es un repo\n", + "\n", + " # Lista para almacenar info resumida de cada repositorio\n", + " repos_info_list = []\n", + "\n", + " for repo in repos_data:\n", + " repo_name = repo.get(\"name\")\n", + " repo_url = repo.get(\"html_url\")\n", + " stars = repo.get(\"stargazers_count\")\n", + " language = repo.get(\"language\")\n", + " last_update = repo.get(\"updated_at\")\n", + "\n", + " # Vamos a formatear la fecha de última actualización para mostrar solo la fecha (YYYY-MM-DD)\n", + " if last_update:\n", + " last_update = last_update.split(\"T\")[0] # toma solo la parte antes de 'T'\n", + "\n", + " # Guardar la info en un diccionario\n", + " repo_info = {\n", + " \"name\": repo_name,\n", + " \"url\": repo_url,\n", + " \"stars\": stars,\n", + " \"language\": language,\n", + " \"last_update\": last_update\n", + " }\n", + " repos_info_list.append(repo_info)\n", + "\n", + " # Imprimir para verificar (formato básico)\n", + " print(\"Repositories ---------------------\")\n", + " for info in repos_info_list:\n", + " print(info[\"name\"])\n", + " print(\" View Repo:\", info[\"url\"])\n", + " print(\" Stars:\", info[\"stars\"])\n", + " print(\" Language:\", info[\"language\"])\n", + " print(\" Last Updated:\", info[\"last_update\"])\n", + " print() # línea en blanco entre repos\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "26Ma6aC_b6AC", + "outputId": "9f094ebc-bba2-4125-915c-266e18f52cfb" + }, + "execution_count": 3, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Repositories ---------------------\n", + "1590A\n", + " View Repo: https://github.com/torvalds/1590A\n", + " Stars: 389\n", + " Language: OpenSCAD\n", + " Last Updated: 2025-08-11\n", + "\n", + "libdc-for-dirk\n", + " View Repo: https://github.com/torvalds/libdc-for-dirk\n", + " Stars: 274\n", + " Language: C\n", + " Last Updated: 2025-08-03\n", + "\n", + "libgit2\n", + " View Repo: https://github.com/torvalds/libgit2\n", + " Stars: 209\n", + " Language: C\n", + " Last Updated: 2025-08-04\n", + "\n", + "linux\n", + " View Repo: https://github.com/torvalds/linux\n", + " Stars: 199404\n", + " Language: C\n", + " Last Updated: 2025-08-11\n", + "\n", + "pesconvert\n", + " View Repo: https://github.com/torvalds/pesconvert\n", + " Stars: 443\n", + " Language: C\n", + " Last Updated: 2025-07-27\n", + "\n", + "subsurface-for-dirk\n", + " View Repo: https://github.com/torvalds/subsurface-for-dirk\n", + " Stars: 337\n", + " Language: C++\n", + " Last Updated: 2025-07-27\n", + "\n", + "test-tlb\n", + " View Repo: https://github.com/torvalds/test-tlb\n", + " Stars: 806\n", + " Language: C\n", + " Last Updated: 2025-08-05\n", + "\n", + "uemacs\n", + " View Repo: https://github.com/torvalds/uemacs\n", + " Stars: 1524\n", + " Language: C\n", + " Last Updated: 2025-08-11\n", + "\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "# Diccionario para acumular bytes de código por lenguaje en todos los repos\n", + "total_bytes_by_lang = {}\n", + "\n", + "for repo in repos_info_list:\n", + " repo_name = repo[\"name\"]\n", + " # Construir la URL de lenguajes para este repositorio\n", + " lang_url = f\"https://api.github.com/repos/{username}/{repo_name}/languages\"\n", + "\n", + " # Hacer la petición a la URL de lenguajes\n", + " response_langs = requests.get(lang_url)\n", + " if response_langs.status_code != 200:\n", + " print(f\"Error obteniendo lenguajes de {repo_name}: {response_langs.status_code}\")\n", + " continue # saltar al siguiente repo si hay error\n", + " languages_data = response_langs.json() # diccionario de lenguajes y bytes\n", + "\n", + " # Sumar los bytes de cada lenguaje al total global\n", + " for lang, bytes_count in languages_data.items():\n", + " if lang in total_bytes_by_lang:\n", + " total_bytes_by_lang[lang] += bytes_count\n", + " else:\n", + " total_bytes_by_lang[lang] = bytes_count\n", + "\n", + "# Calcular porcentajes de uso de cada lenguaje\n", + "most_used_languages = []\n", + "if total_bytes_by_lang:\n", + " total_bytes = sum(total_bytes_by_lang.values())\n", + " for lang, bytes_count in total_bytes_by_lang.items():\n", + " percentage = (bytes_count / total_bytes) * 100\n", + " # Guardar tupla (porcentaje, lenguaje) para ordenar después\n", + " most_used_languages.append((percentage, lang))\n", + "\n", + " # Ordenar de mayor a menor porcentaje\n", + " most_used_languages.sort(reverse=True, key=lambda x: x[0])\n", + "\n", + " # Preparar lista de strings \"Lenguaje (X%)\"\n", + " lang_output_list = []\n", + " for perc, lang in most_used_languages:\n", + " # Formatear el porcentaje con 1 decimal\n", + " perc_str = f\"{perc:.1f}%\"\n", + " # Opcional: podemos redondear .0 para mostrarlo como entero si no tiene decimal\n", + " if perc_str.endswith(\".0%\"):\n", + " perc_str = perc_str.replace(\".0%\", \"%\")\n", + " lang_output_list.append(f\"{lang} ({perc_str})\")\n", + "\n", + " # Generar el string final de lenguajes más usados\n", + " languages_output = \", \".join(lang_output_list)\n", + "\n", + " # Imprimir la línea de \"Most Used Languages\"\n", + " print(\"Most Used Languages\")\n", + " print(languages_output)\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "mYXUhOUJcAoP", + "outputId": "4be3890d-a9db-4bab-d17b-6ed825eaf812" + }, + "execution_count": 4, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Most Used Languages\n", + "C (97.9%), Assembly (0.7%), Shell (0.4%), Python (0.3%), C++ (0.2%), Makefile (0.2%), Rust (0.1%), Perl (0.1%), XSLT (0%), QML (0%), Roff (0%), SmPL (0%), CMake (0%), Yacc (0%), Awk (0%), Lex (0%), JavaScript (0%), HTML (0%), Jinja (0%), M4 (0%), Java (0%), TeX (0%), UnrealScript (0%), CSS (0%), QMake (0%), Gherkin (0%), OpenSCAD (0%), Linker Script (0%), Dockerfile (0%), Objective-C++ (0%), R (0%), Clojure (0%), MATLAB (0%), sed (0%), XS (0%), RPC (0%), Batchfile (0%)\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "def format_star_count(stars):\n", + " \"\"\"Convierte un número de estrellas en formato abreviado con K/M si es grande.\"\"\"\n", + " if stars is None:\n", + " return \"0\"\n", + " if stars < 1000:\n", + " return str(stars)\n", + " elif stars < 1000000:\n", + " # Formato K (miles)\n", + " # Dividir por 1000.0 para obtener decimal, una cifra decimal si es necesario\n", + " k = stars / 1000.0\n", + " # Si el valor tiene decimal .0, mostrar entero, si no, una cifra decimal\n", + " if k.is_integer():\n", + " return f\"{int(k)}K\"\n", + " else:\n", + " return f\"{k:.1f}K\"\n", + " else:\n", + " # Formato M (millones) por si algún repositorio tuviera >= 1 millón de estrellas\n", + " m = stars / 1000000.0\n", + " if m.is_integer():\n", + " return f\"{int(m)}M\"\n", + " else:\n", + " return f\"{m:.1f}M\"\n", + "\n", + "# Ordenar los repositorios por número de estrellas descendente\n", + "repos_sorted_by_stars = sorted(repos_info_list, key=lambda x: x[\"stars\"] or 0, reverse=True)\n", + "\n", + "# Tomar top 3 repos (o menos si no hay tantos)\n", + "top_repos = repos_sorted_by_stars[:3]\n", + "\n", + "# Imprimir encabezado de Most Starred Repos\n", + "print(\"Most Starred Repos\")\n", + "for repo in top_repos:\n", + " name = repo[\"name\"]\n", + " star_count = repo[\"stars\"] or 0\n", + " star_str = format_star_count(star_count)\n", + " print(f\"{name} – {star_str} stars\")\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "UidO26MucGoH", + "outputId": "00216f87-8026-4985-8dfd-fcf8c3c0e158" + }, + "execution_count": 5, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Most Starred Repos\n", + "linux – 199.4K stars\n", + "uemacs – 1.5K stars\n", + "test-tlb – 806 stars\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "import requests\n", + "\n", + "username = \"torvalds\"\n", + "\n", + "# 1. Obtener datos de perfil del usuario\n", + "user_url = f\"https://api.github.com/users/{username}\"\n", + "response = requests.get(user_url)\n", + "if response.status_code != 200:\n", + " print(f\"Error al obtener datos del usuario: {response.status_code}\")\n", + "else:\n", + " user_data = response.json()\n", + " name = user_data.get(\"name\")\n", + " login = user_data.get(\"login\")\n", + " bio = user_data.get(\"bio\")\n", + " public_repos = user_data.get(\"public_repos\")\n", + " followers = user_data.get(\"followers\")\n", + " following = user_data.get(\"following\")\n", + " location = user_data.get(\"location\")\n", + " profile_url = user_data.get(\"html_url\")\n", + "\n", + " # 2. Obtener lista de repositorios del usuario\n", + " repos_url = f\"https://api.github.com/users/{username}/repos?per_page=100\"\n", + " response_repos = requests.get(repos_url)\n", + " if response_repos.status_code != 200:\n", + " print(f\"Error al obtener repositorios: {response_repos.status_code}\")\n", + " else:\n", + " repos_data = response_repos.json()\n", + " repos_info_list = []\n", + " for repo in repos_data:\n", + " repo_name = repo.get(\"name\")\n", + " repo_url = repo.get(\"html_url\")\n", + " stars = repo.get(\"stargazers_count\")\n", + " language = repo.get(\"language\")\n", + " last_update = repo.get(\"updated_at\")\n", + " if last_update:\n", + " last_update = last_update.split(\"T\")[0]\n", + " repos_info_list.append({\n", + " \"name\": repo_name,\n", + " \"url\": repo_url,\n", + " \"stars\": stars,\n", + " \"language\": language,\n", + " \"last_update\": last_update\n", + " })\n", + "\n", + " # 3. Calcular lenguajes más usados\n", + " total_bytes_by_lang = {}\n", + " for repo in repos_info_list:\n", + " repo_name = repo[\"name\"]\n", + " lang_url = f\"https://api.github.com/repos/{username}/{repo_name}/languages\"\n", + " resp_lang = requests.get(lang_url)\n", + " if resp_lang.status_code == 200:\n", + " for lang, bytes_count in resp_lang.json().items():\n", + " total_bytes_by_lang[lang] = total_bytes_by_lang.get(lang, 0) + bytes_count\n", + " most_used_langs_str = \"\"\n", + " if total_bytes_by_lang:\n", + " total_bytes = sum(total_bytes_by_lang.values())\n", + " # Obtener porcentaje y ordenar\n", + " lang_percentages = []\n", + " for lang, bytes_count in total_bytes_by_lang.items():\n", + " perc = (bytes_count / total_bytes) * 100\n", + " lang_percentages.append((perc, lang))\n", + " lang_percentages.sort(reverse=True, key=lambda x: x[0])\n", + " # Formatear los dos primeros lenguajes (por ejemplo) o todos si se prefiere\n", + " formatted_langs = []\n", + " for perc, lang in lang_percentages[:len(lang_percentages)]:\n", + " perc_str = f\"{perc:.1f}%\"\n", + " if perc_str.endswith(\".0%\"):\n", + " perc_str = perc_str.replace(\".0%\", \"%\")\n", + " formatted_langs.append(f\"{lang} ({perc_str})\")\n", + " most_used_langs_str = \", \".join(formatted_langs)\n", + "\n", + " # 4. Calcular repos más estrellados (top 3)\n", + " repos_sorted_by_stars = sorted(repos_info_list, key=lambda x: x[\"stars\"] or 0, reverse=True)\n", + " top_repos = repos_sorted_by_stars[:3]\n", + " def format_star_count(stars):\n", + " if stars is None:\n", + " return \"0\"\n", + " if stars < 1000:\n", + " return str(stars)\n", + " elif stars < 1000000:\n", + " k = stars / 1000.0\n", + " return (f\"{k:.1f}K\" if not k.is_integer() else f\"{int(k)}K\")\n", + " else:\n", + " m = stars / 1000000.0\n", + " return (f\"{m:.1f}M\" if not m.is_integer() else f\"{int(m)}M\")\n", + "\n", + " # 5. Imprimir todos los resultados formateados\n", + " print(f\"# GitHub Profile: {login}\")\n", + " print(f\"# Name: {name}\")\n", + " print(f\"# Username: {login}\")\n", + " print(f\"# Bio: {bio if bio else ''}\")\n", + " print(f\"# Public Repos: {public_repos}\")\n", + " print(f\"# Followers: {followers:,}\".replace(\",\", \"K\") if followers and followers >= 1000 else f\"# Followers: {followers}\")\n", + " print(f\"# Following: {following}\")\n", + " print(f\"# Location: {location if location else ''}\")\n", + " print(f\"# Profile URL: {profile_url}\")\n", + " print(\"\\n# Repositories ---------------------\\n\")\n", + " for repo in repos_info_list:\n", + " print(f\"# {repo['name']}\")\n", + " print(f\"# View Repo ({repo['url']})\")\n", + " star_str = format_star_count(repo['stars'])\n", + " print(f\"# Stars: {star_str}\")\n", + " print(f\"# Language: {repo['language'] if repo['language'] else 'N/A'}\")\n", + " print(f\"# Last Updated: {repo['last_update']}\")\n", + " print(\"\") # línea en blanco después de cada repositorio\n", + " print(\"\\n# Most Used Languages\")\n", + " print(f\"# {most_used_langs_str}\")\n", + " print(\"\\n# Most Starred Repos\")\n", + " for repo in top_repos:\n", + " star_str = format_star_count(repo['stars'])\n", + " print(f\"# {repo['name']} – {star_str} stars\")\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "0UmQ7QOPcNKH", + "outputId": "2a12b1da-da83-494d-a469-cd41b1224a3c" + }, + "execution_count": 6, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "# GitHub Profile: torvalds\n", + "# Name: Linus Torvalds\n", + "# Username: torvalds\n", + "# Bio: \n", + "# Public Repos: 8\n", + "# Followers: 243K336\n", + "# Following: 0\n", + "# Location: Portland, OR\n", + "# Profile URL: https://github.com/torvalds\n", + "\n", + "# Repositories ---------------------\n", + "\n", + "# 1590A\n", + "# View Repo (https://github.com/torvalds/1590A)\n", + "# Stars: 389\n", + "# Language: OpenSCAD\n", + "# Last Updated: 2025-08-11\n", + "\n", + "# libdc-for-dirk\n", + "# View Repo (https://github.com/torvalds/libdc-for-dirk)\n", + "# Stars: 274\n", + "# Language: C\n", + "# Last Updated: 2025-08-03\n", + "\n", + "# libgit2\n", + "# View Repo (https://github.com/torvalds/libgit2)\n", + "# Stars: 209\n", + "# Language: C\n", + "# Last Updated: 2025-08-04\n", + "\n", + "# linux\n", + "# View Repo (https://github.com/torvalds/linux)\n", + "# Stars: 199.4K\n", + "# Language: C\n", + "# Last Updated: 2025-08-11\n", + "\n", + "# pesconvert\n", + "# View Repo (https://github.com/torvalds/pesconvert)\n", + "# Stars: 443\n", + "# Language: C\n", + "# Last Updated: 2025-07-27\n", + "\n", + "# subsurface-for-dirk\n", + "# View Repo (https://github.com/torvalds/subsurface-for-dirk)\n", + "# Stars: 337\n", + "# Language: C++\n", + "# Last Updated: 2025-07-27\n", + "\n", + "# test-tlb\n", + "# View Repo (https://github.com/torvalds/test-tlb)\n", + "# Stars: 806\n", + "# Language: C\n", + "# Last Updated: 2025-08-05\n", + "\n", + "# uemacs\n", + "# View Repo (https://github.com/torvalds/uemacs)\n", + "# Stars: 1.5K\n", + "# Language: C\n", + "# Last Updated: 2025-08-11\n", + "\n", + "\n", + "# Most Used Languages\n", + "# C (97.9%), Assembly (0.7%), Shell (0.4%), Python (0.3%), C++ (0.2%), Makefile (0.2%), Rust (0.1%), Perl (0.1%), XSLT (0%), QML (0%), Roff (0%), SmPL (0%), CMake (0%), Yacc (0%), Awk (0%), Lex (0%), JavaScript (0%), HTML (0%), Jinja (0%), M4 (0%), Java (0%), TeX (0%), UnrealScript (0%), CSS (0%), QMake (0%), Gherkin (0%), OpenSCAD (0%), Linker Script (0%), Dockerfile (0%), Objective-C++ (0%), R (0%), Clojure (0%), MATLAB (0%), sed (0%), XS (0%), RPC (0%), Batchfile (0%)\n", + "\n", + "# Most Starred Repos\n", + "# linux – 199.4K stars\n", + "# uemacs – 1.5K stars\n", + "# test-tlb – 806 stars\n" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 936335c..0000000 --- a/README.md +++ /dev/null @@ -1,118 +0,0 @@ -![logo_ironhack_blue 7](https://user-images.githubusercontent.com/23629340/40541063-a07a0a8a-601a-11e8-91b5-2f13e4e6b441.png) - -# LAB | APIs -
- -

Learning Goals

-
- - This lab allows you to practice and apply the concepts and techniques taught in class. - - Upon completion of this lab, you will be able to: - -- Use Python libraries such as requests to extract data from APIs, and convert extracted data into a suitable data structure. - -
-
- -
- -
- -
- - -## Introduction - -Welcome to the world of music data exploration! In this lab, you will venture into the realm of the Spotify API using SpotiPy, a Python library that allows you to interact with Spotify's vast music catalog and playlist data. - -### **Objective** - -The objective of this lab is to acquaint you with the fundamental operations of the Spotify API using SpotiPy. You will learn how to authenticate with the API, perform searches for tracks and artists, and retrieve information about playlists, among other things. - -### **Lab Sections** - -This lab comprises two main sections: - -#### **Section 1: Discovering New Music through Your Favorite Artists** - -In this section, you will use the Spotify API to explore the top tracks of your favorite artists and discover related artists. By the end, you'll have the opportunity to create a playlist featuring your favorite tracks and those of related artists. - -#### **Section 2: Unraveling the World of Playlists** - -In the second section, you will delve into Spotify's featured playlists. You'll learn how to fetch information about these playlists, explore their details, and extract track and artist data from them. - -
- -Let's embark on this musical journey into the world of Spotify API exploration! - -
- -**Happy coding!** :heart: - - -## Requirements - -- Fork this repo -- Clone it to your machine - -## Getting Started - -Complete the challenges in the `Jupyter Notebook` file. Follow the instructions and add your code and explanations as necessary. - -## Submission - -- Upon completion, run the following commands: - -```bash -git add . -git commit -m "Solved lab" -git push origin master -``` - -- Paste the link of your lab in Student Portal. - - -## FAQs -
- I am stuck in the exercise and don't know how to solve the problem or where to start. -
- - If you are stuck in your code and don't know how to solve the problem or where to start, you should take a step back and try to form a clear question about the specific issue you are facing. This will help you narrow down the problem and come up with potential solutions. - - - For example, is it a concept that you don't understand, or are you receiving an error message that you don't know how to fix? It is usually helpful to try to state the problem as clearly as possible, including any error messages you are receiving. This can help you communicate the issue to others and potentially get help from classmates or online resources. - - - Once you have a clear understanding of the problem, you will be able to start working toward the solution. - - [Back to top](#faqs) - -
- - -
- I am unable to push changes to the repository. What should I do? -
- -There are a couple of possible reasons why you may be unable to *push* changes to a Git repository: - -1. **You have not committed your changes:** Before you can push your changes to the repository, you need to commit them using the `git commit` command. Make sure you have committed your changes and try pushing again. To do this, run the following terminal commands from the project folder: - ```bash - git add . - git commit -m "Your commit message" - git push - ``` -2. **You do not have permission to push to the repository:** If you have cloned the repository directly from the main Ironhack repository without making a *Fork* first, you do not have write access to the repository. -To check which remote repository you have cloned, run the following terminal command from the project folder: - ```bash - git remote -v - ``` -If the link shown is the same as the main Ironhack repository, you will need to fork the repository to your GitHub account first and then clone your fork to your local machine to be able to push the changes. - -**Note**: You should make a copy of your local code to avoid losing it in the process. - - [Back to top](#faqs) - -
- diff --git a/lab-apis.ipynb b/lab-apis.ipynb deleted file mode 100644 index e923554..0000000 --- a/lab-apis.ipynb +++ /dev/null @@ -1,566 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "27422808-8a16-4be1-897f-57b379af8991", - "metadata": {}, - "source": [ - "# Lab | APIs" - ] - }, - { - "cell_type": "markdown", - "id": "50f30950-3e31-499a-92ea-1535422c570b", - "metadata": {}, - "source": [ - "In order to use the `Spotify` API (`SpotiPy`), create an account in `Spotify` and follow [these](https://developer.spotify.com/documentation/general/guides/app-settings/) steps. " - ] - }, - { - "cell_type": "markdown", - "id": "a0479b95-6ca5-415e-b894-1f5cb17b055b", - "metadata": {}, - "source": [ - "## Authentication and initializing the API" - ] - }, - { - "cell_type": "markdown", - "id": "47d71611-c617-4972-a0c3-7090c24b399c", - "metadata": {}, - "source": [ - "Save your client ID and your client secret in your preferred way, and read it or load it into the following variables:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ea44c82a-5c07-4dbc-beb2-bba2601bb75e", - "metadata": {}, - "outputs": [], - "source": [ - "CLIENT_ID = \"\"\n", - "CLIENT_SECRET = \"\"" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "319cfd4e-f6fb-4419-80e0-e3983cd25e43", - "metadata": {}, - "outputs": [], - "source": [ - "CLIENT_ID = \"4109b2d9f5014671863bb2df1d1fbdd3\"\n", - "CLIENT_SECRET = \"5cb719fae80c4191a9c0b288f51bfe50\"" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "04e12954-fd70-4311-88a5-fb7e2c29799c", - "metadata": {}, - "outputs": [], - "source": [ - "# If you havent done so, install the spotipy wrapper\n", - "!pip install spotipy" - ] - }, - { - "cell_type": "markdown", - "id": "dc0e86da-8846-4207-84c3-cd20b9e01d0e", - "metadata": {}, - "source": [ - "Once you have done it, we will start initializing the API." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "03034bc6-9858-412a-83b7-18abdc345d7e", - "metadata": {}, - "outputs": [], - "source": [ - "import spotipy\n", - "from spotipy.oauth2 import SpotifyClientCredentials\n", - "\n", - "#Initialize SpotiPy with user credentials\n", - "sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=CLIENT_ID,\n", - " client_secret=CLIENT_SECRET))\n" - ] - }, - { - "cell_type": "markdown", - "id": "8fed9628-08d7-4290-a4be-5527696b01c5", - "metadata": {}, - "source": [ - "## Using the search method" - ] - }, - { - "cell_type": "markdown", - "id": "6575a3c6-f25a-4905-b1f3-c0efd50dcc1e", - "metadata": {}, - "source": [ - "Now, let's use the search method by introducing a \"query\". For example, let's try searching for \"Lady Gaga\":" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7772a1e0-9692-4d04-a590-76111a272d8d", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "results = sp.search(q='Lady Gaga', limit=50)\n", - "results" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "edc14c95-474b-4e2a-aea3-bdfd0a205546", - "metadata": {}, - "outputs": [], - "source": [ - "results.keys() # We can see that we only have tracks" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ad8ef934-1dbb-4008-ac8e-f5c29823fe6a", - "metadata": {}, - "outputs": [], - "source": [ - "results[\"tracks\"].keys() # Let's check the values" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "004b7814-4dd5-408e-b7ba-1da87f9250cb", - "metadata": {}, - "outputs": [], - "source": [ - "results[\"tracks\"][\"href\"] # Query we have searched " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7285cedd-fbe1-47cf-98d5-a7fdc3e5c8b8", - "metadata": { - "scrolled": true, - "tags": [] - }, - "outputs": [], - "source": [ - "results[\"tracks\"][\"items\"] #items (actual tracks)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "529fff56-47d3-4d78-8ff5-9530fe290d1d", - "metadata": {}, - "outputs": [], - "source": [ - "results[\"tracks\"][\"limit\"]#Limit we have chosen" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "92c64c57-3bd2-4d42-bbd1-84a040f1e02a", - "metadata": {}, - "outputs": [], - "source": [ - "results[\"tracks\"][\"next\"] #link to the next page (next 50 tracks)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f5ccdf79-5d9e-40de-adb9-2cc1e5b7c74a", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "results[\"tracks\"][\"offset\"] # Actual offset (starting point)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "356730c1-60a2-4ea8-bd2c-e0522bab8a4d", - "metadata": {}, - "outputs": [], - "source": [ - "results[\"tracks\"][\"previous\"] #Previous search" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7c44c8fd-63ea-45ba-94bd-5c5e8e1458b3", - "metadata": {}, - "outputs": [], - "source": [ - "results[\"tracks\"][\"total\"] # Number of matches" - ] - }, - { - "cell_type": "markdown", - "id": "7a127c64-3274-4ecc-aa0f-83ae34af4655", - "metadata": {}, - "source": [ - "## Exploring the tracks" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6c3541a2-0fd2-41e0-9b27-60a7dc36c4cb", - "metadata": { - "scrolled": true, - "tags": [] - }, - "outputs": [], - "source": [ - "results[\"tracks\"][\"items\"][0] # Explore the first song" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f2c35eb2-3ea6-4329-9f29-7c062f466638", - "metadata": {}, - "outputs": [], - "source": [ - "results[\"tracks\"][\"items\"][0].keys() # We will focus on album, artists, id, name, popularity, type and uri" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "889ca3c3-b0c8-4037-96fb-6add847f537f", - "metadata": {}, - "outputs": [], - "source": [ - "# Track artists\n", - "results[\"tracks\"][\"items\"][0][\"artists\"] " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a9c6a0b2-cea7-48ff-8c51-179d15388aa2", - "metadata": {}, - "outputs": [], - "source": [ - "# Track artists names\n", - "for artist in results[\"tracks\"][\"items\"][0][\"artists\"]:\n", - " print(artist[\"name\"])" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6a826e9c-d2e7-4537-a82c-3dc3a2b80b9f", - "metadata": {}, - "outputs": [], - "source": [ - "# Track ID\n", - "results[\"tracks\"][\"items\"][0][\"id\"] " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a5bd871b-6087-4680-819c-1a1d8ba879bc", - "metadata": {}, - "outputs": [], - "source": [ - "# Track name\n", - "results[\"tracks\"][\"items\"][0][\"name\"] " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "812661f1-29db-452f-a719-cdfbe95ba9f6", - "metadata": {}, - "outputs": [], - "source": [ - "# Popularity index\n", - "results[\"tracks\"][\"items\"][0][\"popularity\"] " - ] - }, - { - "cell_type": "markdown", - "id": "0e81c762-e6c5-424e-a4eb-12ab45dffb9f", - "metadata": {}, - "source": [ - "Spotify songs are identified by either a \"url\", a \"uri\", or an \"id\". \n", - "\n", - "- The `id` is an alphanumeric code, and it's the nuclear part of the identifier.\n", - "\n", - "- The `uri` contains \"spotify:track\" before the id. An uri is useful because it can be searched manually in the Spotify app.\n", - "\n", - "- The `url` is a link to the song on the Spotify web player.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8bcdccfc-dde9-4f4b-8af5-3caa335b89b5", - "metadata": {}, - "outputs": [], - "source": [ - "results[\"tracks\"][\"items\"][0][\"uri\"]" - ] - }, - { - "cell_type": "markdown", - "id": "71c3c9c1-4ec2-42bf-a243-b21105ae1699", - "metadata": {}, - "source": [ - "## Exercise 1: Discovering New Music through Your Favorite Artists\n", - "\n", - "**Objective:** \n", - "Uncover new music by exploring the top tracks of your favorite artists and their related artists.\n", - "\n", - "**Instructions:**\n", - "\n", - "1. **List Your Favorite Artists**:\n", - " - Make a list of your three favorite artists and store it in a variable named `artists`.\n", - " - Example: `artists = [\"Los Fabulosos Cadillacs\", \"Manu Chao\", \"Muchachito Bombo Infierno\"]`.\n", - "\n", - "2. **Fetch Top Tracks**:\n", - " - Write a function named `get_top_tracks`.\n", - " - This function should accept an artist's name and return the name of the first 5 top tracks by that artist.\n", - " - Use the function `get_top_tracks` to get the first 5 top tracks for each artist in your `artists` list and store the results in a new list named `top_tracks_list`.\n", - "\n", - "3. **Discover Related Artists**:\n", - " - Write a function named `find_related_artists`.\n", - " - This function should accept an artist's name and return the names of the first 5 artists related to the provided artist.\n", - " - Store the results in a list named `related_artists_list`.\n", - "\n", - "**Challenge:** \n", - "Combine the above steps to create a playlist that includes the top tracks of your favorite artists and the top tracks of the artists related to them." - ] - }, - { - "cell_type": "markdown", - "id": "0c442378-e26f-47c8-b4f1-b4fa07089935", - "metadata": {}, - "source": [ - "**Hint Section for 3. **Discover Related Artists**:**\n", - "\n", - "1. **Getting Artist ID**:\n", - " - Remember that every artist on Spotify has a unique identifier: their `id`. To get the related artists, you first need to fetch the ID of the given artist.\n", - " - Consider using the `sp.search` method to query the artist's name. The method requires a `q` parameter, which is your query (in this case, the artist's name). It also has a `limit` parameter, which specifies the number of tracks it returns. In this case, 1 track is enough, since we just want the artist ID. \n", - " - Each track in the results has an associated 'artists' field. This field is a list containing details about all artists involved in that track.\n", - " - For most tracks, especially those by a single artist, this list will contain one artist. From this artist's details, you can extract the 'id' field, which is the unique identifier for that artist on Spotify.\n", - "\n", - "\n", - "3. **Fetching Related Artists**:\n", - " - Once you have the artist's ID, you can use another SpotiPy method to fetch related artists. Think about which SpotiPy method allows you to get related artists using an artist's ID. Here is the documentation link: https://spotipy.readthedocs.io/en/2.22.1/. \n", - " - This method will return a list of related artists. You'll need to extract the relevant details (artist names) from this list.\n", - "\n", - "4. **Iterating for Multiple Artists**:\n", - " - Once you have a function that returns related artists names for one artist, you can use a list comprehension to apply this function to a list of artist names.\n", - "\n", - "5. **Testing**:\n", - " - Always test your function with one artist name first. Once you're confident it works, then apply it to the entire list.\n", - "\n", - "Remember, the key is to break the problem down into manageable steps. Use the SpotiPy documentation as a resource to understand available methods and their return structures." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "29694252-f217-454d-8881-681b2b6eeb1e", - "metadata": {}, - "outputs": [], - "source": [ - "# Your answer here" - ] - }, - { - "cell_type": "markdown", - "id": "94ad5fdc-22e5-4521-8aa1-c6833eb7e949", - "metadata": {}, - "source": [ - "## Playlists\n", - "\n", - "The `sp.featured_playlists()` method in `spotipy` fetches a list of Spotify's featured playlists at a given moment. These are curated playlists that Spotify often highlights on the platform's homepage. The method provides a snapshot of the playlists that are being promoted or featured by Spotify at the time of the request.\n", - "\n", - "Once you've fetched the featured playlists, you can extract their IDs (and other details)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "25fb0cf8-c13a-41b0-b8f8-7e0700fd1e41", - "metadata": {}, - "outputs": [], - "source": [ - "sp.featured_playlists() # We get a playlist id of a playlist we like" - ] - }, - { - "cell_type": "markdown", - "id": "90f558f3-c638-4df4-b5a4-e24f7847d52a", - "metadata": {}, - "source": [ - "### Getting a Playlist's Details\n", - "To fetch details about a specific playlist, you can use the playlist method. You'll need the playlist's Spotify ID." - ] - }, - { - "cell_type": "markdown", - "id": "0eef529f-617f-4ea3-8156-07472ac8e6d5", - "metadata": {}, - "source": [ - "In this example, we will use the following playlist id: *37i9dQZF1DXd9zR7tdziuQ*" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "46d35121-9256-4cf4-81f5-118b87f7af32", - "metadata": {}, - "outputs": [], - "source": [ - "playlist_id = \"37i9dQZF1DXd9zR7tdziuQ\"\n", - "playlist = sp.playlist(playlist_id)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5260f67f-6024-4fee-8449-30904f03bf76", - "metadata": {}, - "outputs": [], - "source": [ - "print(playlist['name']) # Print the playlist's name\n", - "print(playlist['description']) # Print the playlist's description" - ] - }, - { - "cell_type": "markdown", - "id": "13bc8631-69f0-4b98-9cc9-5baecbaea9ba", - "metadata": {}, - "source": [ - "### Getting Tracks from a Playlist\n", - "If you want to get the tracks from a specific playlist, you can use the playlist_tracks method." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "69c78f8d-7e6a-4d15-bcbb-fc93edb82433", - "metadata": {}, - "outputs": [], - "source": [ - "tracks = sp.playlist_tracks(playlist_id)\n", - "for track in tracks['items']:\n", - " print(track['track']['name']) # Print each track's name" - ] - }, - { - "cell_type": "markdown", - "id": "2775714d-acc7-4555-96bd-2c541ab0855e", - "metadata": {}, - "source": [ - "### Getting Artists from a Playlist\n", - "\n", - "To extract all the artists from the tracks in a playlist, you'd typically follow these steps:\n", - "\n", - "1. Fetch the playlist's tracks.\n", - "2. Iterate through each track.\n", - "3. For each track, extract the associated artists." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "65c5e5c4-f186-42c6-b136-4ef02b0b01ff", - "metadata": {}, - "outputs": [], - "source": [ - "# List to store unique artist names\n", - "artists_list = []\n", - "\n", - "for track_item in tracks['items']:\n", - " track = track_item['track']\n", - " for artist in track['artists']:\n", - " artist_name = artist['name']\n", - " if artist_name not in artists_list: # This ensures each artist is added only once\n", - " artists_list.append(artist_name)\n", - "\n", - "print(artists_list)" - ] - }, - { - "cell_type": "markdown", - "id": "7b52207e-a4f0-4f90-9f4e-3170d7f0f3fe", - "metadata": {}, - "source": [ - "## Exercise 2: Unraveling the World of Playlists\n", - "\n", - "\n", - "1. **Featured Exploration**: \n", - " - Fetch the list of Spotify's current featured playlists. \n", - " - Extract and display the names and IDs of the top 5 featured playlists.\n", - " \n", - "2. **Deep Dive**:\n", - " - Choose any one of the top 5 featured playlists (you can choose the one you personally find most interesting or simply pick one randomly).\n", - " - Fetch and display its name, description, and total track count.\n", - "\n", - "3. **Track-tastic**:\n", - " - Extract and display the names of the first 10 tracks in the chosen playlist.\n", - "\n", - "4. **Artistic Flair**:\n", - " - Create a dictionary where the keys are the names of the first 10 tracks, and the values are lists containing the names of the artists associated with each track.\n", - " - For example: `{\"TrackName1\": [\"Artist1\", \"Artist2\"], \"TrackName2\": [\"Artist3\"]}`\n", - " " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ed92d961-9646-4375-a386-ccc320a958f5", - "metadata": {}, - "outputs": [], - "source": [ - "# Your answer here" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.13" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -}