Creating a REST client to get Tracks from Spotify REST API - Part2 Save and Refresh Token
Last Chapter: Creating a REST client to get Tracks from Spotify REST API - Part1 Check out token
Git link: https://github.com/ecelg/InterSystems-IRIS-as-a-Spotify-REST-client
Ok... Now we can check out a token but it will be expired in 3600 seconds.
There are 2 questions come up🤔
1. How to save this token????🙄
2. How to refresh this token????🤨🤔
Lets come back to the API document https://developer.spotify.com/documentation/web-api/tutorials/getting-started
Base on my understanding, this piece of API do not have a token called refresh_token, as a result, we can assume the logic like following
.png)
OK let start writing the class method getToken
Open the class rest.utli.requestUtli.cls
Add the following class method
ClassMethod getToken(apiname As%String = "") As%String [ Language = objectscript ]
{
//w ##class(rest.utli.requestUtli).getToken("Spotify")set token="0"set rowid=##class(rest.class.apiinfo).checkRowid(apiname)
if (rowid'=0)
{
kill a
set a=##class(rest.class.apiinfo).%OpenId(rowid)
set token=a.accesstoken
// check expireyset tokenexpired=0set refreashbefore=a.refreshbefore
if (token="")||(refreashbefore="")
{
set tokenexpired=1
}else
{
set rfdate=+$p(refreashbefore,",",1)
set rftime=+$p(refreashbefore,",",2)
if (rftime<+$p($h,",",2))
{
if (rfdate<=+$p($h,",",1)) set tokenexpired=1
}else
{
if (rfdate<+$p($h,",",1)) set tokenexpired=1
}
}
// checkout tokenif (token="")||(tokenexpired=1)
{
set b={}.%FromJSON(##class(rest.utli.requestUtli).checkoutToken("Spotify"))
//w b."access_token",",",b."token_type",",",b."expires_in",!//set the update beforeset rbdate=$p($h,",",1)
set rbtime=+$p($h,",",2)+b."expires_in"if (rbtime>86400)
{
set rbdate=+rbdate+1set rbtime=+rbtime-86400
}
//w rbdate_","_rbtime,!set a.accesstoken=b."access_token"set a.tokentype=b."token_type"set a.expiresin=b."expires_in"set a.refreshbefore=rbdate_","_rbtime
set a.updateat=$hset std=a.%Save()
return a.accesstoken
}
}
return token
}Save it
.png)
Now open a terminal and test the code
.png)
Run the following line
w ##class(rest.utli.requestUtli).getToken("Spotify").png)
Yeah!!! 😆It is working!!!!