I want to get a list of all tracks - resp. the IDs of those tracks - from a certain user. So I'm sending following request to the API (JavaSript SDK):
callPath = "/users/3817541/tracks";
SC.get(callPath,function(obj)
{
console.log(obj);
});
What I get back is an Array of Objects, each of them stuffed with all the track's detail out of which i can extract the IDs - but the transmission of all the unnecessary data slows down my application (I'm actually running this request for multiple users).
Is there any way to tell the API to return just a specific property (ID) of every object instead of the whole cake?
Related
I am currently writing an endpoint to return data for videos from two youtube channels. Currently using the method of making the request via url and fetch() and want to continue using this. How do I construct the URL such that it returns the data for two channels and not one. My current URL is shown below:
lets say channel1 = foo and I want to query for channel2 = bar also, without using a second url and making a second query.
let url = `https://www.googleapis.com/youtube/v3/search?key=${process.env.YOUTUBE_API_KEY}&part=snippet&q=foo`;
Any help would be greatly appreciated.
Your example call uses "q=foo" where you say foo is channel1. However "q" is for the query term so the API would search all channels for "foo".
To limit a search to a channel you would use the "channelId" parameter, and you an only use one per call.
See https://developers.google.com/youtube/v3/docs/search/list
I'm trying to get some data using Youtube data api -v3 playlistItems. I'm able to get all the data that comes with playlistItems perfectly. However, I need more data than what playlistItems offers. For example, I would like to get the view counts, comment count, and all the statistics
I know I could use /youtube/v3/videos to get the statistics but I have been trying this and it is not working for me. Please help. Thanks.
export function buildVideosRequest(amount = 12, loadDescription = false, nextPageToken) {
let fields = 'nextPageToken,prevPageToken,items(contentDetails/videoId,id,snippet(channelId,channelTitle,publishedAt,thumbnails/medium,title)),pageInfo(totalResults)';
if (loadDescription) {
fields += ',items/snippet/description';
}
return buildApiRequest('GET',
'/youtube/v3/playlistItems',
{
part: 'snippet,contentDetails',
maxResults: amount,
playlistId: 'PLvahqwMqN4M0zIUkkXUW1JOgBARhbIz2e',
pageToken: nextPageToken,
fields,
}, null);
}
Upon invoking the PlaylistItems.list endpoint, you obtain a result set of which each item is a playlistItems resource JSON object.
That JSON object doesn't contain the info you're interested in (view count, comment count, etc). This kind of info -- as you alluded yourself -- is obtainable through the Videos.list API endpoint.
That is that you have to collect all video IDs that you're interested in into an array, then invoke repeatedly the Videos.list endpoint, passing to it an id parameter assigned properly.
Note that this endpoint's id property allows you to reduce the number of endpoint calls, since the id may be specified as a comma-separated list of video IDs (at most 50). Hence, if you have for example an array of 114 video ID's, then you may issue only 3 calls to Videos.list.
I am creating a tampermonkey script that will read a line of text that contains an artist and song title from a webpage and will create a link that will open a new tab to the first result that is returned from the youtube api. My issue is that when the page is loaded and say there are 5 songs on this particular page, according to my youtube api dashboard, I am making about 1200 api requests for that single page. Im guessing that its because when I query a single artist/song, its getting every result on its server. I tried limiting my maxResults to 1, but this doesn't help. Since youtube decreased the number of queries a single API gets, I would like to know if there is a way to reduce the number of queries it makes. Realistically, I just need the first result from the GET request, since chances are that will be the correct video.
here is a snippet of my code that parses through the json data:
function getLink(artist, song){
// API Key
var key = "MY_KEY";
// Setup url for api
var url = 'https://www.googleapis.com/youtube/v3/search?part=id&q=' + artist + "-" + song + '&maxResults=1&key=' + key;
// call api and get videoId
var xhReq = new XMLHttpRequest();
xhReq.open("GET", url, false);
xhReq.send(null);
var id = JSON.parse(xhReq.responseText);
return id.items[0].id.videoId;
}
I'm not sure if I'm looking at the same Google doc, but it says the part parameter should be snippet for a Search:list call. I know different calls take up different quota amounts. Using the query below I get only one song returned. It seems to use only the normal 100 units of quota required for Search:list:
https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=Adele+Hello&fields=items(id(videoId))&key=API_key
It returns:
{
"items": [
{
"id": {
"videoId": "YQHsXMglC9A"
}
}
]
}
Be sure to escape artist and title with something like encodeURIComponent. It could be that the strings in those variables are breaking the intended URL you want to process.
Even more, if you do a test with the Youtube API sandbox, you could check it by yourself. In my case I've tried "Radiohead" and "Paranoid Android" with 3 max results and it's working fine. See here
What I'm trying to achieve is an effective way of passing each item found in a specific attribute through a JSON request in jQuery, so that I can gather information about it from an API. The API is Twitch and each data attribute is a streamers name.
Each streamer would be defined like so -
<div streamer='streamer_name'></div>
and from the API I'd like to gather their status and information. However, the Twitch API does not showcase information about offline streamers in the original API url, and so I have to use two API URL's to get all the required data.
I have created something that works, and as I'm rather new to this, I've most likely missed out on important features required to make this as effective as possible.
$('[streamer]').each(function() {
var data = $(this);
var streamer = $(data).attr('streamer');
$.getJSON('https://api.twitch.tv/kraken/streams/' + streamer, function(x) {
if (x.stream != null) {
$(data).append(
//online data
);
} else {
$.getJSON('https://api.twitch.tv/kraken/channels/' + streamer, function(x) {
$(data).append(
//offline data
);
});
}
})
})
http://jsfiddle.net/W4Km8/8801/ for an example of what this code actually does.
EDIT: There is also a way to search for multiple streamers at once, although again, it does not show any data for those that are offline.
https://api.twitch.tv/kraken/streams?channel=riotgames,scrags
EDIT2: To be more specific about my doubts, occasionally it will append the data incorrectly and will break the page layout, or not show up at all. This happens quite frequently upon page refreshes.
Thanks
I'm having a hard time writing my question succinctly and clearly, so let me describe what I'm working with.
I'm building a web application that:
has it's own API hosted on a subdomain (https://api.example.com)
has the main application hosted on the tld (https://www.example.com)
the tld doesn't have any database access, but instead interacts with the API to work with data
the tld authenticates with the api through OAuth and stores the access token and access token secret in a session
when the session ends, the access token is no longer used, thus logging the user out
I have a route in the tld (let's call it /ajax for this question) that the javascript calls (GET, PUT, POST, OR DELETE) to make requests to the api. This way, nobody ever has to see the access token, access token secret, consumer key, or consumer secret.
The way I see it, the access token and access token secret are really the only things I need to store in a session since I can grab everything else using the API, but instead of making a call every single time for every piece of data I need, I think some things should persist, like aspects of the user's profile, layout preferences, etc.
What is the best way for me to accomplish this? Local storage? Cookies? Should I scrap this and just store it in sessions?
And if you have some time, what other best practices are there for building sites like this that I may not know of?
You are on the right track I would say, but store your data in JavaScript primarily. And couple it with Local Storage when suitable.
When I build apps such as the one you are describing I usually take care to set up JavaScript representations of the data I receive via the API.
One such representation could look as follows below. Bear in mind that my example code below makes a couple of assumptions.
It makes the assumption that you have an api object defined which takes care of API calls, and invokes a callback on completion.
that the data returned by the API is JSON that simply can be assigned to a JavaScript variable,
That the JSON returned is a list of objects, each with an "id" field.
That you have some sort of event object, I usually build my own custom events that basically carry function objects as listeners and when fired go through the listeners and invoke the functions with or without a payload depending on the situation.
Data container example:
MYAPP.data.BaseContainer = function (api_url, loadedEvent) {
var self = {
// Array to store the data returned via the APIs
_data : [],
// The API URL used to fetch data
api_url : api_url,
// Boolean flag to signify whether the _data variable has been populated
is_loaded : false,
// The even to fire once _data has been populated
loadedEvent : loadedEvent,
/**
* Returns the state of the is_loaded variable
*/
loaded : function () {
return self.is_loaded;
},
/**
* Takes an ID and returns any member of the _data array
* that has that ID.
*
* #param id : an String or integer representing the ID.
* #returns {Object}
*/
byId : function (id) {
var toReturn = null;
for (var i = 0, len = self._data.length; i < len; i++) {
if (self._data[i].id == id) {
toReturn = self._data[i];
break;
}
}
return toReturn;
},
/**
* Returns the entire _data array.
*/
all : function () {
return self._data;
},
/**
* This simple callback just stores the json response in
* its entirety on the _data variable.
*/
callback : function(data) {
self._data = data;
self.is_loaded = true;
loadedEvent.fire(self._data);
},
/**
* Calls the API, if no callback has been specified as a parameter
* self.callback is used.
*/
getFromAPI : function(callback) {
if (typeof callback === 'undefined') {
callback = self.callback;
}
api.get(self.api_url, callback);
}
};
self.getFromAPI();
return self;
};
With this blueprint I can now create specific data containers like this:
/**
* Stores a list of "friends" gotten from the API.
* This is basically an instance of the BaseContainer object defined above.
*/
MYAPP.data.Friends = (function () {
var self = MYAPP.data.BaseContainer("API_URL_TO_FECTH_FRIENDS_LIST", FriendsLoadedEvent);
return {
byId : self.byId,
all : self.all,
loaded : self.loaded
};
}());
As soon as this code is run, an API call is made, and the FriendsLoadedEvent will be fired when it is done. So, to put it bluntly, I use JavaScript to store my stuff usually. But if you want to throw LocalStorage into the mix that is easy too!
Just add local storage code to the BaseContainer object that first detects whether the client actually supports localstorage, and if so mirror the _data field in local storage. This is handy to keep often used data quickly available between sessions. Use the readily available JSON parsing tools to convert the data from JSON to LocalStorage "text"and back.
Just keep in mind that you cannot rely on LocalStorage as your primary data structure, you have no guarantee that the client supports it, and even when it does the upper bounds for how much data you can actually store is different between the browsers. So use it to store data that:
You want access to very often,
that you feel should just be there, immediately as soon as the user logs in,
and that does not change often enough to warrant refreshing API calls constantly.
Congratulation! You've answered most of your question already. If you want to persist user data, you'll need to use something like local storage or cookies. In your case local storage is best. With cookies, each page request sends to cookies along in the header.
Best of Luck with your app.