Link de Git: https://github.com/ecelg/InterSystems-IRIS-as-a-Spotify-REST-client
Recientemente se me ocurrió una idea: ¿cómo puedo poner mi lista de reproducción en IRIS? 🧐
Al mismo tiempo, me dijeron que debía pagar mi suscripción de Spotify 💸💸... oooh... ¿y si obtengo algunos datos de la API de Spotify? Así que empecé a investigar sobre eso.
Como en la mayoría de los desarrollos, comencemos con la documentación de la API: https://developer.spotify.com/documentation/web-api
Para obtener los datos, se requiere solicitar un token de acceso en la URL del endpoint de token. 🧐
curl -X POST "https://accounts.spotify.com/api/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=your-client-id&client_secret=your-client-secret"
Shell SessionShell Session
Pero antes de eso, debéis comprobar vuestro client_id y client_secret en el Dashboard
creando una aplicación.
entoces
comprobad la api
comprobad la configuración
copiad el client_id y client_secret
Vale, todo está listo 😀 Vamos con ello!!!!!😁
1. Configurad una clase Persistent para almacenar la información de la API.
sustituir el código como en el siguiente y guardad
Class rest.class.apiinfo Extends (%Persistent, %JSON.Adaptor)
{
Property apiname As %String;
Property clientid As %String(%JSONFIELDNAME = "client_id");
Property clientsecret As %String(%JSONFIELDNAME = "client_secret");
Property granttype As %String(%JSONFIELDNAME = "grant_type");
Property tokentype As %String(%JSONFIELDNAME = "token_type");
Property accesstoken As %String(%JSONFIELDNAME = "access_token", MAXLEN = 200);
Property expiresin As %String(%JSONFIELDNAME = "expires_in");
Property refreshtoken As %String(%JSONFIELDNAME = "refresh_token", MAXLEN = 200);
Property authurl As %String(MAXLEN = 100);
Property authheader As %String(MAXLEN = 100);
Property apiurl As %String(MAXLEN = 100);
Property refreshbefore As %String;
Property updateat As %String;
ClassMethod checkRowid(apiname As %String = "") As %Integer [ Language = objectscript ]
{
//w ##class(rest.class.apiinfo).checkRowid("Spotify")
set rtn=0
set rowid=""
&sql(select id into :rowid from rest_class.apiinfo where apiname=:apiname )
//w rowid,!
if rowid'="" set rtn=rowid
return rtn
}
}
ObjectScriptObjectScript
2. Insertad la información de la API en la tabla
insertad la información de la api en la tabla
ejemplo SQL
insert into rest_class.apiinfo
(apiname, apiurl, authurl, clientid, clientsecret, granttype, authheader)
values
('Spotify', 'https://api.spotify.com/v1', 'https://accounts.spotify.com/api/token', 'b43bf136********************', '45ffde***************', 'client_credentials', 'application/x-www-form-urlencoded')
SQLSQL
verificadlo
SELECT
ID, accesstoken, apiname, apiurl, authheader, authurl, clientid, clientsecret, expiresin, granttype, refreshbefore, refreshtoken, tokentype, updateat
FROM rest_class.apiinfo
SQLSQL
3. Configurad un cliente REST para comprobar el token.
Parece que hay varias opciones
Opción 1
Creando operaciones REST en Producción, pero ¿cómo insertar el encabezado "Content-Type: application/x-www-form-urlencoded"? 😓 Dejadme investigar más... Usando el adaptador HTTP Outbound, ok... parece que... necesito revisar más... Usando la respuesta HTTP... ooo lo siento... realmente no lo entiendo porque no hay un ejemplo paso a paso para mí... me rindo. 😭
Opción 2
Python request, parece mucho más fácil de entender, empecemos con la opción 2.
3a. Install the requests library
Si necesitáis configurar vuestro propio Python para IRIS después de la versión 2024.3, podéis consultar la guía Flexible Python Runtime para IRIS en Windows Server.
En PowerShell, escribid lo siguiente para instalar la biblioteca requests:
python -m pip install requests
Shell SessionShell Session
En PowerShell, escribid lo siguiente para instalar la biblioteca iris:
python -m pip install iris
Shell SessionShell Session
3b. Escribid una clase %RegisteredObject para comprobar el token.
Crejad la carpeta utli dentro de la carpeta rest.
cread la clase requestUtli.cls
escribid la class method checkoutToken
Class rest.utli.requestUtli Extends %RegisteredObject
{
ClassMethod checkoutToken(apiname = "", withgrandtype = 1) As %String [ Language = python ]
{
#w ##class(rest.utli.requestUtli).checkoutToken("Spotify")
import requests
import json
import iris
# get the apiinfo object by apiname
rowid=iris.cls('rest.class.apiinfo').checkRowid(apiname)
a=iris.cls('rest.class.apiinfo')._OpenId(rowid)
# parameter perparation
api_baseurl=a.authurl
params=""
if withgrandtype==1:
#print ('grandtype ='+a.granttype)
params="grant_type="+a.granttype+"&client_id="+a.clientid+"&client_secret="+a.clientsecret
else:
#print ('without grandtype')
params="client_id="+a.clientid+"&client_secret="+a.clientsecret
contenttype=a.authheader
headers={"Content-Type":contenttype}
api_url=api_baseurl+"?"+params
#print(api_url)
del a
# post it
response = requests.post(api_url,headers=headers, verify=False)
#print(response)
if response.status_code==200:
return json.dumps(response.json())
else:
return response.status_code
}
}
ObjectScriptObjectScript
Guardad el código
4. Abrid una terminal para probar si está funcionando o no.
Ejecutad el siguiente comando para realizar la prueba.
w ##class(rest.utli.requestUtli).checkoutToken("Spotify")
Shell SessionShell Session
¡Síii! ¡El token se ha verificado correctamente! 😁