新しい投稿

検索

ダイジェスト
· 2024年12月30日

Nuevas publicaciones en la Comunidad de InterSystems, 23-29 diciembre

23-29 diciembreWeek at a GlanceInterSystems Developer Community
記事
· 2024年12月30日 2m read

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

 


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 expirey
		set tokenexpired=0
		set 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 token
		if (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 before
			set rbdate=$p($h,",",1)
			set rbtime=+$p($h,",",2)+b."expires_in"
			if (rbtime>86400)
			{
				set rbdate=+rbdate+1
				set 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=$h
			set std=a.%Save()
			
			return a.accesstoken
		}
	}
	return token
}

Save it

 


Now open a terminal and test the code

Run the following line

w ##class(rest.utli.requestUtli).getToken("Spotify")

Yeah!!! 😆It is working!!!!

ディスカッション (0)1
続けるにはログインするか新規登録を行ってください
ダイジェスト
· 2024年12月30日
ダイジェスト
· 2024年12月30日

InterSystems 开发者出版物,十二月 23 - 29, 2024,摘要

記事
· 2024年12月29日 4m read

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

 

Recently, I come up an idea in my mind that how can I put my playlist on IRIS.🧐

At the same time, I was told to pay for my Spotify subscription💸💸... ooo.. how about to get some data from the Spotify API... so I started to do study about it.

 

Like most of the development, let's start from Documentation of  the API https://developer.spotify.com/documentation/web-api

In order to get the data, i am required to request an access token from for the token endpoint URL.🧐

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"

but before that I should check out my client_id and my client_secret from the Dashboard 

by Create app

then

check the api

check the setting

copy the client_id and client_secret

 


OK every thing is ready😀 Let's go!!!!!😁

1. Setup a  Persistent class to store the API information

replace the code as following and save

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
}
}

 

 


2. Insert the API information into the table

insert the api information into the table

example 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')

verify it

SELECT
ID, accesstoken, apiname, apiurl, authheader, authurl, clientid, clientsecret, expiresin, granttype, refreshbefore, refreshtoken, tokentype, updateat
FROM rest_class.apiinfo

 


3. Setup a REST client to check out the token

It seems there are many options, 

Option 1

Creating REST Operations in Productions, but how to insert the header  "Content-Type: application/x-www-form-urlencoded" 😓. Let me check further Using the HTTP Outbound Adapter, ok.... seems... need to check further... Using the HTTP Response, ... oooo sorry... really cannot understand as there no step by step example for me.... give up.😭  

Option 2

Python request, seems much easier to understand, let's start with option 2

 

3a. Install the requests library

If you need to setup your own python for IRIS after version 2024.3 you may reference to Use the Flexible Python Runtime Feature for IRIS on Windows Server

In the powershell type the following to install the requests library

python -m pip install requests

In the powershell type the following to install the iris library

python -m pip install iris

3b. Write a  %RegisteredObject class for check out the token

create the folder utli under the folder rest

create the class requestUtli.cls 

write the 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
}

}

Save the code

 


4. Open a terminal to test if it is working or not

run the following command for testing

w ##class(rest.utli.requestUtli).checkoutToken("Spotify")

Yeah!! the token is check out successfully!!!!😁


2 Comments
ディスカッション (2)2
続けるにはログインするか新規登録を行ってください