How to get Youtube video title with v3 URL API in javascript w Ajax & JSON
Solution 1
I got it working using
https://www.googleapis.com/youtube/v3/videos?id=itemId&key=apiKey&fields=items(snippet(title))&part=snippet
and
alert(data.items[0].snippet.title);
So, not much wrong with the syntax! But I found that the problem was really in the backend when setting up the Google API's 'allowed referers'. With V3 API, you can select which referers the API should belong to, so others cannot simply steal your API and use it. So the API will work if the request is originated from the domain name/IP you specify. When I don't give it restrictions, the code works, but when I do enter my domain it fails! I entered .mydomainname.com/ , the same format as it was suggested, but it errors out somehow.. Now I've got figure out why.
Solution 2
The following jquery code will fetch the title of the video.
$.ajax({
url: "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key="+ apiKey + "&fields=items(snippet(title))&part=snippet",
dataType: "jsonp",
success: function(data){
console.log(data.items[0].snippet.title);
},
error: function(jqXHR, textStatus, errorThrown) {
alert (textStatus, + ' | ' + errorThrown);
}
});
Kamy D
Updated on June 05, 2022Comments
-
Kamy D almost 2 years
I am only trying to fetch Youtube video's title. Can't seem to figure it. So far I have this:
q = 'https://www.googleapis.com/youtube/v3/videos?id='+ itemId +'&key='+ ytApiKey +'&fields=items(snippet(channelId,title,categoryId))&part=snippet' ; $.ajax({ url: q, dataType: "jsonp", success: function(data){ alert(data.items[0].title); console.log(data.snippet.title); }, error: function(jqXHR, textStatus, errorThrown) { alert (textStatus, + ' | ' + errorThrown); } });
Thanks,
-
Jason Axelrod over 8 yearsWouldn't it be bad to do things this way? Since you would have to expose your apiKey to the javascript, which could be viewed by anyone?
-
Jason Axelrod over 8 yearsWouldn't it be bad to do things this way? Since you would have to expose your apiKey to the javascript, which could be viewed by anyone?
-
Kamy D over 8 yearsMy understanding is that you can link your domain to your API key in Google's setup page! That way Youtube knows where the API call is originated from, therefore other people cannot simply use your API key. I ran into some issue getting it to work though, so I had a question open. There is a comment there, but I haven't tried it yet: stackoverflow.com/questions/28032237/…
-
binaryBigInt over 6 yearsWhat can I do if I get this error message:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
-
Kamy D over 6 yearsIt’s CORS issue. You can look it up. Different ways Of handling it if you are using jQuery, or calling from backend servers. And also check this post: stackoverflow.com/questions/47523265/…