How to get spotify artist id for the spotify endpoint url? - javascript

I am trying to get the top ten tracks for an artist, but I don't know how to get Spotify id for that particular artist? this is the end point.
GET /v1/artists/{id}/top-tracks
The premise is this, i should be able to type an artist name, and I should get the JSON data for the top ten tracks.
function test() {
var query = $('#searchArtist').val();
console.log(query);
$.ajax({
url: 'https://api.spotify.com/v1/artists/' + query + '/top-tracks?country=IN',
success: function(response) {
console.log(response)
}
})
}
$('#search').on('click', test);
Am I supposed to first authorize? Because I searched the document and fetching the top ten tracks data doesn't require authorization.
Also, to let you know. There is no backend environment here, as mentioned in the docs, it is not required for simple data fetch.

What TZHX said. You need two seperate requests. Javascript in the browser is not my main environment. I will explain with curl and jq in bash. Hopefully it is clear enough.
$ API_ARTIST_URL=$(curl -s 'https://api.spotify.com/v1/search?q=Daft+Punk&type=artist' | jq -r '.artists.items[0].href')
$ echo $API_ARTIST_URL
https://api.spotify.com/v1/artists/4tZwfgrHOc3mvqYlEYSvVi
$ curl -s "$API_ARTIST_URL/top-tracks?country=US" | jq -r '.tracks[].name'
Get Lucky - Radio Edit
One More Time
Instant Crush
Get Lucky
Lose Yourself to Dance
Around The World
Harder Better Faster Stronger
Doin' it Right
Something About Us
Give Life Back to Music
Another detail. ?country=IN will not yield any results, because Spotify has not launched in India yet.

Related

Getting list of emails in google contacts email directory from Google People API using Google Scripts

How do I get People.searchDirectoryPeople() working? This is what I have got:
People.searchDirectoryPeople().setQuery("Justin");
I was able to get https://developers.google.com/people/quickstart/apps-script working in apps-script but nothing else so far.
My goal is to search through the directory, either by email or by name (preferably learn how to do both) - Thanks in advance!
The Google Apps Script advanced services are basically wrappers for their REST API counterparts. So typically, you'd need to look up the REST documentation to figure out how to properly leverage API endpoints.
However, in this case, the documentation for the searchDirectoryPeople endpoint does not explain query syntax. Fortunately, query syntax is common to many Google APIs, and is documented under the Drive API. The following links should help you to get moving in the right direction:
https://developers.google.com/people/api/rest/v1/people/searchDirectoryPeople
https://developers.google.com/drive/api/v3/search-files
There are relevant code sample available in the second link under the Node.js tab.
Also, be sure to take advantage of the Apps Script editor's code completion features to figure out which params you can pass to an endpoint.
Here's a simple script to search the directory:
function searchDirectory() {
var results = People.People.searchDirectoryPeople({
query : "Tom",
readMask: "names,emailAddresses,phoneNumbers",
sources: "DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"
});
Logger.log("results: " + JSON.stringify(results, null, 0));
results.people?.forEach(person => Logger.log(person.names?.map(name => name.displayName) + ", " +
person.emailAddresses?.map(email => email.value) + ", " +
person.phoneNumbers?.map(phone => phone.value)));
}
The first log will output the raw results object, the loop will then go over each person in the results and log their name, emails & phones.

Youtube-Search NPM package gives weird results

I'm using the youtube-serach NPM library with express to find the first youtube video with a song name.
app.get("/search", (req, res) => {
var search = require("youtube-search");
var SONG = req.query.SONG;
var opts = {
maxResults: 10,
key: "[REDACTED]"
};
search(SONG, opts, function(err, results) {
if (err) return console.log(err);
res.json(results);
});
});
When I set SONG to "DJ Turn It Up", the first result when you search in the youtube search bar is the youtube video "Yellow Claw - DJ Turn It Up [Official Full Stream]" by Mad Decent.
When I use youtube-search to sear for "DJ Turn It Up" none of the 10 results are the Mad Decent video, and the first result is actually a scene from Riverdale with the song in it, with 1/33 of the views!?!
This happens with other tracks I search too.
I don't get it! I've tried other NPM packages like ytsearch with no luck either!
Is there anyway to fine tune this or a better alternative?!
You can use the REST API https://www.googleapis.com/youtube/v3/search and pass some parameter to the API call.
The parameters are q - that defines the artist name or album name, key - a key is generated by making google project use that key and the last parameter is part - part parameter in the request specifies which portions of the resource are to be included in the response. For knowing the details like publish date, channel id etc you can pass snippet in your part parameter.
For more details visit - https://developers.google.com/youtube/v3/sample_requests

Search for artist id by name

I am delving into spotify and javascript is not my main programming language so I managed to get some snippets together from a code that uses ajax (which I would rather not use) but still it returns nothing so I am wondering if some more experienced people out there could help me get started with a template to call the api.
My goal for this test is to search an artist name and get the first result (I expect many names will return multiple artists)
Most of what is in the documentation is curl and I didn't find the demos very helpful.
What I have so far is something like this:
function getArtistName (artistName) {
var artistID;
var searchArtists = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: query,
type: 'artist',
'accessToken': 'BQBvW70gHJ20Flc8cHErqg8s72bfTePbssblED-gpEuHFr_Yezesbthok8qaKBmjzo2WjWo9J7ZcTpSwvV8MZ_cW_E7UkrG_HF2R6gFQcqfdupgYGmoYsdRdt1q3tq2NU3pPgauuzmFLkUpdAuNp3shdVXJz2SzvnA',
'query': artistName,
limit: '1.'
},
success: function (response) {
//resultsPlaceholder.innerHTML = template(response);
}
});
};
console.log(searchArtists);
return artistID;
}
Some points of confusion:
The key seems to expire. I have a client ID on my profile but I am not sure where I can generate this token other than the "try it out" demo on the site.
What does this actually return, an ID or a JSON?
Here is a demo app that searches tracks using Node.js, or server-side Javascript: https://spotify-quicksearch.glitch.me/
If you click the "Remix this on Glitch" link on the page, you can see and edit the source.
The call to the API is made in server.js. First, we set the client ID and client secret, which are from the dashboard, as you've noted. In this example, we use those to get an access token using the Client Credentials Flow. You can read about all the authentication flows here: https://beta.developer.spotify.com/documentation/general/guides/authorization-guide/
This particular example uses an API wrapper called spotify-web-api-node, which just makes it easier to interact with the API through Javascript functions. To search for artists instead, just change searchTracks to searchArtists.
To answer your second question - all calls to the Spotify API return JSON. You can see the format of the full JSON response here: https://beta.developer.spotify.com/documentation/web-api/reference/search/search/. Roughly, it looks like this:
artists: {
items: [
{
id: <id>,
name: <name>,
...
}
...
]
}
To get the ID from the JSON, you need to parse the JSON object. You can see how I do this in the example in line 21 of client.js. You can modify that code to get just the ID of the first artist like this:
data.artists.items[0].id
Update: made an example that should be even more relevant:
https://spotify-search-artist.glitch.me/

Is it possible to use the Yahoo BOSS OAuth with JavaScript only?

Here is the problem, I have a Google Chrome extension and I want to use the BOSS API in it. The problem is that I do not know if it is possible to use the API without a webserver running.
The documentation does not provide any example using JavaScript. Thus my question:
Is it possible to use the Yahoo BOSS OAuth with JavaScript only?
Probably not...
All the examples Yahoo provides are using server side languages
http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html
First you'd have to figure out how to use OAuth with JavaScript, and how will you obscure your API keys from users in a JS File? If you don't have to worry about that, say you are just using this for personal use. Maybe check out the code sample for Node.JS and modify it for your own uses.
http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html#oauth_js
function yahooSearch(consumerKey, consumerSecret, query, count,
callback_error_data_response){
var webSearchUrl = 'https://yboss.yahooapis.com/ysearch/web';
var finalUrl = webSearchUrl + '?' + qs.stringify({
q: query, //search keywords
format: 'json',
count: count,
});
var oa = new OAuth(webSearchUrl, webSearchUrl, consumerKey, consumerSecret, "1.0", null, "HMAC-SHA1");
oa.setClientOptions({ requestTokenHttpMethod: 'GET' });
oa.getProtectedResource(finalUrl, "GET", '','', callback_error_data_response);
}
// Use this function to make a call back. Make sure to provide the right key, secret and query for this to work correctly yahooSearch('YAHOO CONSUMER KEY GOES HERE', 'YAHOO CONSUMER SECRET GOES HERE', 'SEARCH QUERY', 10, function(error, data, response){
// enter some code here and access the results from the "data" variable in JSON format
});
You can go to YQL Console and then enter your request, you can select Json or XML, after your result is fetched, look at the bottom of the page and then copy the url. You will be able to use that url inside script tags in an html doc and run it with your browser without a server.

How to filter out the most active users from fan page?

I am creating a new website. I want to promote it using another my topic-related web service. I want to send some gifts to people which popularized my first website and fanpage. How to filter out lets say 20 users which likes/shares/comments most of my posts?
Any suitable programming language will be good.
[EDIT]
Ok... to be honest I looking a way to parse a fanpage that is not mine. I want to send gifts to the most active users of fanpage of my competition, to simply bribe them a little :)
There are a number of ways, I'll start with the easiest...
Say there's a brand name or #hashtag involved then you could user the search API as such: https://graph.facebook.com/search?q=watermelon&type=post&limit=1000 and then iterate over the data, say the latest 1000 (the limit param) to find out mode user (the one that comes up the most) out of all the statuses.
Say it's just a page, then you can access the /<page>/posts end point (eg: https://developers.facebook.com/tools/explorer?method=GET&path=cocacola%2Fposts) as that'll give you a list of the latest posts (they're paginated so you can iterate over the results) and this'll include a list of the people who like the posts and who comment on them; you can then find out the mode user and so on.
In terms of the code you can use anything, you can even run this locally on your machine using a simple web server (such as MAMP or WAMP, etc...) or CLI. The response is all JSON and modern languages are able to handle this. Here's a quick example I knocked up for the first method in Python:
import json
import urllib2
from collections import Counter
def search():
req = urllib2.urlopen('https://graph.facebook.com/search?q=watermelon&type=post')
res = json.loads(req.read())
users = []
for status in res['data']:
users.append(status['from']['name'])
count = Counter(users)
print count.most_common()
if __name__ == '__main__':
search()
I've stuck it up on github if you want to refer to it later: https://github.com/ahmednuaman/python-facebook-search-mode-user/blob/master/search.py
When you run the code it'll return an ordered list of the mode users within that search, eg the ones who've posted the most comments with the specific search tag. This can be easily adapted for the second method should you wish to use it.
Based on Ahmed Nuaman answer (please also give them +1), I have prepared this piece of code:
example of usage:
To analyze most active facebook users of http://www.facebook.com/cern
$ python FacebookFanAnalyzer.py cern likes
$ python FacebookFanAnalyzer.py cern comments
$ python FacebookFanAnalyzer.py cern likes comments
notes: shares and inner comments are not supported
file: FacebookFanAnalyzer.py
# -*- coding: utf-8 -*-
import json
import urllib2
import sys
from collections import Counter
reload(sys)
sys.setdefaultencoding('utf8')
###############################################################
###############################################################
#### PLEASE PASTE HERE YOUR TOKEN, YOU CAN GENERETE IT ON:
#### https://developers.facebook.com/tools/explorer
#### GENERETE AND PASTE NEW ONE, WHEN THIS WILL STOP WORKING
token = 'AjZCBe5yhAq2zFtyNS4tdPyhAq2zFtyNS4tdPw9sMkSUgBzF4tdPw9sMkSUgBzFZCDcd6asBpPndjhAq2zFtyNS4tsBphqfZBJNzx'
attrib_limit = 100
post_limit = 100
###############################################################
###############################################################
class FacebookFanAnalyzer(object):
def __init__(self, fanpage_name, post_limit, attribs, attrib_limit):
self.fanpage_name = fanpage_name
self.post_limit = post_limit
self.attribs = attribs
self.attrib_limit = attrib_limit
self.data={}
def make_request(self, attrib):
global token
url = 'https://graph.facebook.com/' + self.fanpage_name + '/posts?limit=' + str(self.post_limit) + '&fields=' + attrib + '.limit('+str(self.attrib_limit)+')&access_token=' + token
print "Requesting '" + attrib + "' data: " + url
req = urllib2.urlopen(url)
res = json.loads(req.read())
if res.get('error'):
print res['error']
exit()
return res
def grep_data(self, attrib):
res=self.make_request(attrib)
lst=[]
for status in res['data']:
if status.get(attrib):
for person in status[attrib]['data']:
if attrib == 'likes':
lst.append(person['name'])
elif attrib == 'comments':
lst.append(person['from']['name'])
return lst
def save_as_html(self, attribs):
filename = self.fanpage_name + '.html'
f = open(filename, 'w')
f.write(u'<html><head></head><body>')
f.write(u'<table border="0"><tr>')
for attrib in attribs:
f.write(u'<td>'+attrib+'</td>')
f.write(u'</tr>')
for attrib in attribs:
f.write(u'<td valign="top"><table border="1">')
for d in self.data[attrib]:
f.write(u'<tr><td>' + unicode(d[0]) + u'</td><td>' +unicode(d[1]) + u'</td></tr>')
f.write(u'</table></td>')
f.write(u'</tr></table>')
f.write(u'</body>')
f.close()
print "Saved to " + filename
def fetch_data(self, attribs):
for attrib in attribs:
self.data[attrib]=Counter(self.grep_data(attrib)).most_common()
def main():
global post_limit
global attrib_limit
fanpage_name = sys.argv[1]
attribs = sys.argv[2:]
f = FacebookFanAnalyzer(fanpage_name, post_limit, attribs, attrib_limit)
f.fetch_data(attribs)
f.save_as_html(attribs)
if __name__ == '__main__':
main()
Output:
Requesting 'comments' data: https://graph.facebook.com/cern/posts?limit=50&fields=comments.limit(50)&access_token=AjZCBe5yhAq2zFtyNS4tdPyhAq2zFtyNS4tdPw9sMkSUgBzF4tdPw9sMkSUgBzFZCDcd6asBpPndjhAq2zFtyNS4tsBphqfZBJNzx
Requesting 'likes' data: https://graph.facebook.com/cern/posts?limit=50&fields=likes.limit(50)&access_token=AjZCBe5yhAq2zFtyNS4tdPyhAq2zFtyNS4tdPw9sMkSUgBzF4tdPw9sMkSUgBzFZCDcd6asBpPndjhAq2zFtyNS4tsBphqfZBJNzx
Saved to cern.html
Read the list of posts on the page at the page's /feed connection and track the user IDs of those users who posted and commented on each post, building a list of who does it the most often.
Then store those somewhere and use the stored list in the part of your system which decides who to send the bonuses to.
e.g.
http://graph.facebook.com/cocacola/feed returns all the recent posts on the cocacola page, and you could track the IDs of the posters, commenters, likers, to determine who are the most active users
write a php or jquery script which is executed when user clicks like or share on your website just before actually sharing/like to fb and record the user info and the post he/she shared/liked. Now you can track who shared your post the most.
PHP/Jquery script will act as middle man, so dont use facebook share/like script directly. I will try to find the code I have written for this method. I have used PHP & Mysql. Try to use JQuery this will give a better result in terms of hidding the process (I mean data will be recorded without reloading the page).
Your question is nice, but it is quite hard.. (Actually, in the beginning, there's a thing that came from my mind that this is impossible. So, I build a quite different solution...) One of the best ways is to create a network where your viewers can register in the form that required the official URLs of their social networking pages, and also, they could choose that they doesn't have this kind of network:
“Do you want to share some of our page? Please register here first..”
So, they can get a specific URL that they've wanted to share when they're in your website, but they doesn't know the they're in tracing when they visited that specific URL.. (Every time a specific URL get visited, an I.P. get tracked and the number of visits get ++1 in a database.) Give them a dynamic URL on the top of your website that's in text area of every pages to track them. Or use scripting to automated the adding of a tracing query string on the URLs of your site.
I think there's a free software to build an affiliate network to make this easy! If your viewers really love your website, they'll registered to be an affiliate. But this thing is different, affiliate network is quite different from a network that mentioned in the paragraphs above..
But I think, you can also use Google Analytics to fully trace some referrals that didn't came from the URLs with dynamic QUERY STRING like Digital Point, but not from the other social network like Facebook 'cause you wouldn't get the exact Referral Paths with that kind of social network because of the query path. However you can use it to track the other networks. Also, AddThis Analytics is good for non-query string URLs.
The two kinds of referrals on Google Analytics are under of “Traffic Sources” menu of STANDARD REPORTS..
Traffic Sources
Sources
Referrals
Social
Network Referrals
This answer is pretty messy, but sometimes, quite useful.. Other than that? Please check these links below:
Publishing with an App Access Token - Facebook Developers
Facebook for Websites - Facebook Developers
Like - Facebook Developers
Open Graph Overview - Facebook Developers

Categories