Skip to content

Instantly share code, notes, and snippets.

@lorenzoferrante
Created December 2, 2018 21:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lorenzoferrante/5038898798410654f678b7734148dde1 to your computer and use it in GitHub Desktop.
Save lorenzoferrante/5038898798410654f678b7734148dde1 to your computer and use it in GitHub Desktop.
Get track or playlist URL from user query
// Base64 encoding of your credentials
let clientID = '<your client id>'
let clientSecret = '<your client secret>'
let cred = clientID + ':' + clientSecret
let credEncoded = Data.fromString(cred).toBase64String()
let auth = 'Basic ' + credEncoded
// Get token
let tokenURL = 'https://accounts.spotify.com/api/token'
var reqToken = new Request(tokenURL)
reqToken.method = 'POST'
reqToken.body = 'grant_type=client_credentials&undefined='
reqToken.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': auth
}
let res = await reqToken.loadJSON()
let token = res['access_token']
let auth2 = 'Bearer ' + token
// Params
var q = encodeURI(URLScheme.parameter('query'))
var t = URLScheme.parameter('type')
let endpoint = 'https://api.spotify.com/v1/search?q=' + q + '&type=' + t
let method = 'GET'
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': auth2
}
// Make the request
let req = new Request(endpoint)
req.method = method
req.headers = headers
// Get the track URL
let json = await req.loadJSON()
var finalURL = ''
if (t == 'track') {
finalURL = json['tracks']['items'][0]['external_urls']['spotify']
} else {
finalURL = json['playlists']['items'][0]['external_urls']['spotify']
}
// Open the track on Spotify
Safari.open(finalURL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment