5

Cómo buscar música con la API Web de Spotify

1330Puntos

hace 9 años

En el mundo de aplicaciones y servicios para reproducir música en línea, Spotify es una de las mejores. Y una de sus características principales es, precisamente, su catálogo. Además, es una herramienta útil para los desarrolladores; ya que les permite crear sus propios desarrollos utilizando su API. En este artículo te mostraré cómo hacer uso de la API Web de Spotify. En resumen, realizaremos los siguientes pasos:
  • Creación de nuestra API en Spotify Developers
  • Deployment de nuestra Aplicación
  • Creación de nuestra Vista Isomórfica con Handlebar JS
Antes de empezar, es aconsejable que revises las últimas actualizaciones en la página de Spotify Developers. En ocasiones hacen cambios en su Web API PHP; y esto se convierte en el principal motivo de fallos en el código.

Creación de nuestra API en Spotify Developers

Lo primero que debemos hacer es entrar a la página de Spotify Developers, iniciar sesión y crear nuestra aplicación. De esta manera generamos automáticamente el Client ID y el Client Secret. Donde dice Redirect URLs, ingresaremos la URL a la que redireccionaremos una vez que iniciemos sesión en nuestra aplicación.

Deployment de nuestra Aplicación

Para iniciar sesión con nuestra cuenta de Spotify crearemos el archivo login.js: [js] // Login con Spotify (function() { var stateKey = 'spotify_auth_state'; function getHashParams() { var hashParams = {}; var e, r = /([^&;=]+)=?([^&;]*)/g, q = window.location.hash.substring(1); while ( e = r.exec(q)) { hashParams[e[1]] = decodeURIComponent(e[2]); } return hashParams; } function generateRandomString(length) { var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }; var userProfileSource = document.getElementById('user-profile-template').innerHTML, userProfileTemplate = Handlebars.compile(userProfileSource), userProfilePlaceholder = document.getElementById('user-profile'); oauthSource = document.getElementById('oauth-template').innerHTML, oauthTemplate = Handlebars.compile(oauthSource), oauthPlaceholder = document.getElementById('oauth'); var params = getHashParams(); var access_token = params.access_token, state = params.state, storedState = localStorage.getItem(stateKey); if (access_token && (state == null || state !== storedState)) { alert('Ocurrio un error durante la Autenticación'); } else { localStorage.removeItem(stateKey); if (access_token) { $.ajax({ url: 'https://api.spotify.com/v1/me', headers: { 'Authorization': 'Bearer ' + access_token }, success: function(response) { userProfilePlaceholder.innerHTML = userProfileTemplate(response); $('#login').hide(); $('#loggedin').show(); } }); } else { $('#login').show(); $('#loggedin').hide(); } document.getElementById('login-button').addEventListener('click', function() { var client_id = 'ACA COLOCAMOS EL CLIENTE ID'; // Tu Client ID var redirect_uri = 'http://www.midominio.com/buscar/'; // Tu Redirect URI (Dirección URL a donde quieres que redireccione luego de iniciar Sesión Con tu cuenta de Spotify.) var state = generateRandomString(16); localStorage.setItem(stateKey, state); var scope = 'user-read-private user-read-email'; var url = 'https://accounts.spotify.com/authorize'; url += '?response_type=token'; url += '&client_id=' + encodeURIComponent(client_id); url += '&scope=' + encodeURIComponent(scope); url += '&redirect_uri=' + encodeURIComponent(redirect_uri); url += '&state=' + encodeURIComponent(state); window.location = url; }, false); } })(); [/js] Ahora, usaremos JavaScript para buscar música. Para lograrlo, crearemos nuestro archivo buscar.js: [js] // Buscador var templateSource = document.getElementById('resultados-template').innerHTML, template = Handlebars.compile(templateSource), resultadosPlaceholder = document.getElementById('resultados'), playingCssClass = 'playing', audioObject = null; var fetchTracks = function (albumId, callback) { $.ajax({ url: 'https://api.spotify.com/v1/albums/' + albumId, success: function (response) { callback(response); } }); }; var searchAlbums = function (query) { $.ajax({ url: 'https://api.spotify.com/v1/search', data: { q: query, type: 'album' }, success: function (response) { resultadosPlaceholder.innerHTML = template(response); } }); }; resultados.addEventListener('click', function (e) { var target = e.target; if (target !== null && target.classList.contains('cover')) { if (target.classList.contains(playingCssClass)) { audioObject.pause(); } else { if (audioObject) { audioObject.pause(); } fetchTracks(target.getAttribute('data-album-id'), function (data) { audioObject = new Audio(data.tracks.items[0].preview_url); audioObject.play(); target.classList.add(playingCssClass); audioObject.addEventListener('ended', function () { target.classList.remove(playingCssClass); }); audioObject.addEventListener('pause', function () { target.classList.remove(playingCssClass); }); }); } } }); document.getElementById('search-form').addEventListener('submit', function (e) { e.preventDefault(); searchAlbums(document.getElementById('query').value); }, false); // Ocultamos nuestro acces token por seguridad if(typeof window.history.pushState == 'function') { window.history.pushState({}, "Hide", "http://www.midominio.com/buscar/"); } [/js]

Creación de nuestra Vista Isomórfica con Handlebar JS

Ahora vamos a crear 2 vistas, una para iniciar sesión y otra para buscar música. Spotify nos aconseja usar isomorfismo. En la documentación oficial aconseja usar Handlebars JS. Pero podemos usar ReactJS y otra librería que sea de nuestro agrado también. Lo primero que debemos hacer es crear la vista para el inicio de sesión:
Login
[js] <div class="container"> <div id="login"> <h1>Inicia Sesión con tu Cuenta de Spotify</h1> <button id="login-button" class="btn btn-primary">Login</button> </div> <div id="loggedin"> <div id="user-profile"> </div> <div id="oauth"> </div> </div> </div> <script src="js/handlebars-v4.0.0.js"></script> <script id="user-profile-template" type="text/x-handlebars-template"> <h1>Logged in as {{display_name}}</h1> <div class="media"> <div class="pull-left"> <img class="media-object" width="150" src="{{images.0.url}}" /> </div> <div class="media-body"> <dl class="dl-horizontal"> <dt>Display name</dt> <dd class="clearfix">{{display_name}}</dd> <dt>Id</dt> <dd>{{id}}</dd> <dt>Email</dt> <dd>{{email}}</dd> <dt>Spotify URI</dt> <dd><a href="{{external_urls.spotify}}">{{external_urls.spotify}}</a></dd> <dt>Link</dt> <dd><a href="{{href}}">{{href}}</a></dd> <dt>Profile Image</dt> <dd class="clearfix"><a href="{{images.0.url}}">{{images.0.url}}</a></dd> <dt>Country</dt> <dd>{{country}}</dd> </dl> </div> </div> </script> <script id="oauth-template" type="text/x-handlebars-template"> <h2>oAuth info</h2> <dl class="dl-horizontal"> <dt>Access token</dt> <dd class="text-overflow">{{access_token}}</dd> </dl> </script> [/js] Ahora creamos la vista para buscar música: [js] <div class="row"> <div class="col-md-12"> <h1>Buscar Artista</h1> Escribe el nombre de un artista y luego has clic en el botón Buscar: <form id="search-form" role="form"> <div class="form-group"> <input type="text" id="query" value="" class="form-control" placeholder="Escribe el nombre de un Artista..."/> </div> <button type="submit" id="search" class="btn btn-primary" />Buscar</button> <button type="reset" id="search" class="btn btn-alert" />Limpiar</button> </form> </div> </div> <div class="row"> <div class="col-md-12"> <div id="resultados"> </div> </div> </div> </div> <!-- Handeblars JS --> <script src="../js/handlebars-v4.0.0.js" type="text/javascript"></script> <script id="resultados-template" type="text/x-handlebars-template"> {{#each albums.items}} <div style="background-image:url({{images.0.url}})" data-album-id="{{id}}" class="cover"> </div> <!-- <h6 class="nombre">{{name}}</h6> <h6 class="popularidad">{{href}}</h6> --> {{/each}} </script> [/js] ¡Y eso es todo! Puedes ver el ejemplo en este DEMO y descargar el código fuente del proyecto en un repositorio en GIT. Y si quieres aprender más acerca de JavaScript, Responsive Design, ECMAScript 6 y más; regístrate hoy a la Carrera de Front-end en Platzi. Y crea aplicaciones yendo más allá de HTML5 y CSS3.  
Juan Ricardo
Juan Ricardo
pepoflex

1330Puntos

hace 9 años

Todas sus entradas
Escribe tu comentario
+ 2
Ordenar por:
2
9Puntos

eso fue increíble. Hice eso con Spotify Premium hack Techbigs y lo encontré genial. Muchísimas gracias

1
2 años

Spotify Premium Mod Apk Você está procurando o Spotify Mod Apk que lhe dá acesso ao Spotify Premium gratuitamente? Se sim, você veio ao lugar certo porque, neste post, vou compartilhar a versão mais recente do Spotify Premium Apk.

1
6 meses

The Samsung A Series 2023 provides a number of different options, so it can cater to the requirements of a wide range of users. From entry-level models to high-end flagships, Samsung ensures that there is a phone suitable for every budget and need. If you are in the market for a new phone teknopediia, you should give serious consideration to this series because it offers attractive rates and solid specifications.

1
4Puntos
6 meses

Las últimas versiones actualizadas de Spotify Premium que uso se han actualizado más rápido en APKClasico

1
un mes

Roblox Fruits scripts refer to custom scripts or programs created by players for the game “Blox Fruits” on the Roblox platform. “Blox Fruits” is a popular Roblox game where players can explore islands, battle enemies, and discover various fruits with unique abilities to run Delta Executor.

2
18Puntos
1
10Puntos
3 meses

[snaptube mod apk for Windows](https://snaptubemodapk.org/) application designed for downloading videos and audio content. While its main focus is video downloads, Snaptube excels in extracting and saving the audio segments of videos.

2
10Puntos
3 meses

snaptube mod apk for Windows application designed for downloading videos and audio content. While its main focus is video downloads, Snaptube excels in extracting and saving the audio segments of videos.

2
4Puntos

Download the best music app after Spotify. Pandora Premium APK is the best app for listen to music online and you can also download it and listen offline.

1
4 meses

Cheating samarinda cheat may provide short-term gains, but its impact is far more significant on what should be a gratifying gaming experience. Understanding the importance of fair play allows us to collectively create an environment that is both fair and enjoyable. ngobrol games

2
9Puntos

Intenté hacerlo en mi aplicación de Spotify y lo hice. gracias

2
3597Puntos
3 años

Creo que esto es PHISING 😉

2
10Puntos
2 años

Spotify is the app I use every day. I usually update the mod apk version of this app to use

1

I believe that with the information you share, it will bring a lot of value to the readers that’s not my neighbor and I hope that they will absorb the good and useful things.

1

kahootcode.com is an extremely helpful game-based learning platform that allows you to easily design, share, and play various learning games and custom quizzes that test your knowledge in real-time. The platform was founded in September 2013 and is available for use in up to 17 languages around the world.

Spotiflyer Online is an amazing app, works offline, and helps you listen to music anywhere without issues. It does not require an active internet connection because it saves songs from the Spotify app for offline experience. The app has eliminated all the

1

Lightroom Mod APK, is a modified version of Lightroom Photo Editor Pro. In the free trial version, some features are available, but to unlock all the features, you need to pay some amount. If you download this modified Lightroom, you can get full access to the premium Adobe Lightroom app, which provides you with all the pro tools to enhance your photo and make it look more professional than others.

Download VSCO MOD APK for Android to enjoy basic and advanced editing with 200+ presets, filters, transition effects, and VSCO X features.

Are you looking for your ideal partner but feel like you’re stuck in a never-ending cycle of bad dates and failed relationships? With the help of a Male Delusion Calculator, you can now evaluate your chances of meeting someone who fits all your criteria.

1

CRM solutions for its distinct issues. Healthcare CRM software improves patient happiness and efficiency by facilitating patient interactions and managing medical data. CRM software goes beyond customer relationship management. It underpins successful marketing, sales, and customer service tactics. CRM Software makes customer data collection and analysis fundamental. Better understand client demands and preferences.

1
303Puntos

Spotify is amazing! It has lots of cool stuff for music lovers. It’s not just a music player, it’s like a magical place full of music. If you’re curious, you can download the special version of it for free from theapkfolder

1
4Puntos

Unlocking the secrets of music with the Spotify Web API is a game-changer! Speaking of efficiency, just like you can seamlessly explore music, make life easier by checking your electricity bill online. Platforms like SEPCO offer the convenience of online bill checking, saving you time and hassle. So, whether you’re grooving to tunes or managing utility bills, the digital era has you covered!

1
4Puntos

Exploring music with the Spotify Web API is like unlocking a treasure trove of melodies! 🎶✨ On another note, let’s shift the rhythm to the Bling2 app – an absolute game-changer in the realm of live-streaming and chat. With Bling2, you’re not just connecting; you’re immersing yourself in a world of interactive experiences. From chat and video calls to sharing precious moments and playing games during conversations, Bling2 is the ultimate destination for fun and social engagement. Experience the beat of connectivity with the dynamic Bling2 apk!

1

Exploring the intricacies of searching for music with the Spotify Web API is both informative and engaging! 🎶✨ Speaking of seamless experiences, discover the wonders of the Zong Super offer. It’s a game-changer in the world of mobile connectivity, offering an array of features that elevate your experience. Check out the Zong Super and unlock a new realm of possibilities in the realm of telecommunications
https://mrinfowala.com/zong-super-star-offer/

1

Exploring the magic of music made easy with Spotify Web API via TV APK! Unlocking a world of tunes right from the comfort of your living room. No need to switch devices; just fire up your TV APK, dive into the Spotify Web API, and let the music journey begin!
https://nineapk.com/rts-tv-apk/

1

" Unlocking the world of music with the Spotify Web API! Thanks to the seamless integration with my favorite streaming app, discovering new tracks and creating playlists has never been smoother. Let the beats guide you!

1

"Exploring the world of music just got even better with the Spotify Web API! Thanks to the Inshot app, I can now search for my favorite tunes seamlessly and enhance my music discovery journey. Cheers to the perfect harmony of technology and creativity!

1
4Puntos

MXL TV - Your free pocket TV. Ditch cable and watch live channels, movies, and shows on your phone or tablet. Add your own playlists, pick from a huge library, and cast to your big screen. All free, all fun! Download MXL TV and cut the cord on entertainment.
https://mxltv.me/

1
4Puntos

Great Article
YouTube Vanced is a modded version of the popular video-sharing app, offering enhanced features beyond the standard YouTube experience. With ad-blocking, background playback, and various customization options, Vanced provides users with a seamless and ad-free viewing experience, making it a preferred choice for those seeking more control and convenience on YouTube.
https://youtubevanced.com.mx/

1
4Puntos

Be sure to visit apksget for an endless selection of modded games with unlimited features.

1

Andrew Biden, a seasoned Financial Analyst with deep insights into the U.S. banking sector, has launched “US Bank Branches,” a comprehensive website providing expert analysis on American banks. With years of experience in financial analysis, Andrew offers a unique perspective on the operations, financial health, and future outlook of banks, from national giants to regional players. This platform is a valuable resource for anyone seeking in-depth, reliable information on the U.S. banking industry.

1
2Puntos

You can download Mods and Injectors for the latest games from APK-FLOAT.

1
4Puntos

Grateful for sharing an excellent blog post! Much appreciated
For more information. instaup

1
4Puntos

Alight Motion Mod APK is developed for people who want to get into advanced video editing without spending a penny. Choose from various advanced editing options to impress your audience for free.
Alight motion xml support mod
Say goodbye to expensive video editing apps because this is your all-in-one tool to create captivating videos without hassle! You can download a version for PC, Android, and iOS from the link. Download the latest Alight Motion Pro+Mod APK that offers premium features for free. Read more to find out why animators and creators love Alight motion!

1

You can make a thumbnail design easily with online youtube thumbnail maker. We have provided everything you need to get started. It only takes a few minutes to create your own images in a couple of easy steps and within a few minutes.

1
3Puntos

A SoundCloud downloader is a nifty online tool that empowers you to convert SoundCloud tracks into MP3 files. It bridges the gap between SoundCloud’s vast music library and your personal collection, ensuring you have access to your preferred music without the need for an internet connection.

1

Spotiflyer Online is a powerful and user-friendly online platform designed to help you download music from Spotify effortlessly. It serves as a bridge between Spotify and your personal music collection, allowing you to listen to your favorite songs offline, anytime, and anywhere.

1
3Puntos

GBWhatsApp es el mod más antiguo de WhatsApp que normalmente se actualiza hasta hoy. Es una versión más impresionantemente personalizada de WhatsApp GBWhatsApp puede ser como OGWhatsApp, pero tiene un montón de funciones aumentadas. No es necesario desinstalar WhatsApp si desea instalar GBwhatsapp apk. GBWhatsApp tiene excelentes atributos; se puede revisar bajo

1

I never knew there is an api for Spotify Premium, thanks for the information.

1
un año

If you want to Downlaod the Spotify Premium on your Android Devices without any ads and with the UI Interface. It has a lot of features and various advantages and disadvantages. But it Advantages are more in nmber then its disadvantages. You can check Spotify Premium APK

1

I sincerely appreciate the information and advice you have shared. Thank you for sharing all this wonderful information. Igtools

1
4Puntos

Are you fond of editing images and videos but don’t have the investment to buy expensive cameras and paid software? If you’re facing such circumstances, Alight Motion MOD APK can change your life. It’s one of the top video editing apps and is available free of cost for users. It can beat the paid software and mobile apps. The reason is that it brings the simplest and most effective way to edit your low-quality videos. Alternatively, it’s the best source to create stunning animation apps and brilliant video pieces. Alight motion pro

1

No doubt, Spotify is a remarkable application, and it always keeps its users satisfied, its MOD APK is always updated with various premium features.

1
16Puntos

Looking for the best PTE coaching in Brisbane? Our guide provides comprehensive tips and resources to choose the right one. Click here!

1

Spotify stands as a true marvel, capable of leaving an indelible impression on anyone who ventures into its musical realm. Within this remarkable application lies a symphony of features, rendering it not merely a music player but an extraordinary gateway to auditory delight. For those whose curiosity is piqued, an enticing avenue awaits — If you’re interested, you can freely download the Mod version of the APK from DLSAPK.

1

I truly enjoy Spotify Premium, as it serves as an excellent music player. If you’re interested, you can download the Mod version of the APK from APKSHOP.

1
4Puntos

Spotify is the app I use every day, and I usually update the MOD APK version of this app to use it with added features.

1

Thank you sir, for sharing this information about how to search song with spotify. This post is really beneficial to me. I have succesfully search any song from spotify on you suggestion. https://telegramchan.com/

1

Lulubox Pro Apk helps you to get unlimited coins, skins, plug ins in your Android iOS video games Let s Download Get Benefits.

1

Wonderfully one of the best content I could find.
the good is applauded and this is worth doing
https://allurefashion.net/

1
un año

Its time to invest your time on cryptocurrency and blockchain technology and telegram is one of the best platform in which you can learn with other members.

Useful resource:Telegram Crypto Groups

1

I literally love this image If you’re looking for a platform to download the best Android APK Mod apps and games, you’ve come to the right place! All Apks Mod is one of the most popular platforms in the world to download Android APK games and APK apps absolutely free without any registration or registration. Just find the app or game you want to download, click the link and install it on your phone. it’s very easy! Download here AllApksMod

1

[Lulubox](https://www.luluboxapkdownload.com/) Pro Apk helps you to get unlimited coins, skins, plug ins in your Android iOS video games Let s Download Get Benefits.

1

Hey, chair lovers. If you searching office chairs for heavy people then you can visit us. Because here we share lots of offices chairs for heavy people according to your criteria. If it helpful then give a review about in the comment section.

1

the season has now come and everyone wants stylish and unique outerwear. but there is limited apparel that everyone can get in a pocket-friendly amount. Yellowstone John Dutton Western Jacket is the latest Example. This jacket is now famous due to its material and unique style.

1

You can certainly see your skills in the paintings you write. The sector hopes for more passionate writers like you who are not afraid to mention how they believe. Always go after your heart. แอพคอลเสียว

1

This is fantastic! Thank you for posting. Please keep spreading!
Are your like anime television series then you should be definitly check out it: <a href=“https://theanimeseason.com/”>The Anime Season</a>

Where you will get anime season update.
1
8Puntos

You can either get FM WhatsApp or YOWhatsApp Because only these two have the kind of reputation to be trusted with.

1

Thank you for the useful information which you shared throughout your blog. I appreciate the way you shared the relevant, precious, and perfect information.
cyber security course

1
4Puntos

You will receive a Sports Welcome Bonus of $2500 in Free Bets if you do decide to register an account with them. Both an iPhone and Android app and a terrific mobile betting site are provided by World777 com. When it comes to their customer assistance, you will have nothing to complain about and they have a large choice of banking alternatives available to players from India.

1
8Puntos

he funniest thing is that you are explaining to people on your website very well, that’s why I like your website very much and I would like to read regularly if you do not want to get knowledge, then you can also check on my website Minecraft Apk

Netflix Mod Apk

1
30387Puntos

Podrían pulir mejor el articulo.

1

APIs work great in the Online world. We can integrate apps, web, services across many platforms. That increases accessibility. Some developers like FouadMods use WA APIs to power their FMWhatsApp. But they also have added advanced features on top of it. I understand the whole point now. Thanks.

1
2Puntos

Gracias por compartir, tu artículo es muy bueno. Estoy usando Spotify Premium, esta aplicación escucha buena música y también incluye muchos artistas famosos en el mundo,

1

Esta es una aplicación muy atractiva en HapMod.Com, además puedes hacer referencia a más aplicaciones y juegos gratuitos con la última versión de [URL=‘https://hapmod.com/’]APK Mod[/URL].

1
1604Puntos

Al menos, utilicen Gist Github para poner el código. Porfavor…