YouTube Data API (v3): Introduction With Spring Boot - DZone
文章推薦指數: 80 %
Java YouTube Data API. Learn more about app development using the YouTube Data API. YouTube is a video-sharing website where users can view ...
Like
(4)
Comment
Save
Tweet
14.94K
Views
JointheDZonecommunityandgetthefullmemberexperience.
JoinForFree
LearnmoreaboutappdevelopmentusingtheYouTubeDataAPI
YouTubeisavideo-sharingwebsitewhereuserscanviewanduploadvideos.Forbothwebandappdevelopment,sometimesweneedtoaccessinformationfromYouTubevideos.
Youmayalsolike:
BuildaSpringBootAPIUsingSpringDataJPAandHibernate
Inthiscase,wehavetousetheAPI'sprovidedbyGoogledevelopers.ThemaingoalofthisarticleistointroducehowwecanuseYoutTubeAPIswithJava.Here,wewilluseSpringBootwithHibernateJPAandlibrariesfromGoogletoimplementtheexample.
Pre-Conditions
ToaccesstheYouTubeDataAPI,wehavetofollowsomebasicinstructions,likecreateaGoogleaccount,aproject,credentials,etc.Maybe,itwouldbebettertofollowtheseinstructionslisted here . Ifwefollowthestepsfromthislink,wefirstneedtheClientId,APIkey,clientsecret,etc.
Next,wecanstartourimplementation.Weneedtoputourcredentialsintotheapplication.propertiesfile.ToruntheGitHubexample(linkisgivenbelow),wealsoneedtosetupJava,MySQL,andGradle.
APIDocs
Inthisarticle,wearemainlyconcernedwithvideoinformation.AYouTubevideopropertymainlycontainsachannel,duration,description,andstatistics(likes,dislikes,etc.).ThesepropertiesareavailableindifferentresourcesoftheYouYubeAPI,suchas video,channel,activity,etc.Theseresourcescanalsoperform list,insert,update,anddeleteoperations.
ThelastpartofthistutorialwillbetocustomizetheYouYubeAPIsothatwecandefinewhatwewant.Justlikethestatisticspartonlycontainsthenumberoflikes,dislikes,pageviews,etc.,the ContentDetails partonlycontainsvideodefinitions,captions,countryrestrictions,etc. —andallofthesecomponentscontainnestedobjects.Combined,wecangetallthepropertiesofavideo,buthere,wewillbefocusingonimportantpartsonly.
Implementation
Withthatsaid,wewillbeimplementingtheYouTubeDataAPIinabitofdifferentway.WewilluseaRESTAPItosaveextracteddatatothedatabase.Fordatabaseentities,wewillcreateacorrespondingJPAentity.Wehavedividedmostofthevideopropertiesdependingonadifferentpart.Entitiesare:
YoutubeChannelInfo
YouTubeVideoInfo
YoutubeVideoStatistics
Additionally,wewillhaveaBaseEntityforcommonproperties,andanotherentity— CrawlingInfo —tokeeptrackofcrawleddata.
Wewillcollectthefollowingdataforthechannelinformation:
@Entity(name="youtube_channel")
@Data
@EqualsAndHashCode(callSuper=true)
publicclassYoutubeChannelInfoextendsBaseEntity{
@Column(name="channel_id")
privateStringchannelId;
@Column(name="name")
privateStringname;
@Column(name="subscription_count")
privatelongsubscriptionCount;
}
Forvideostatistics,wewillcollectthefollowingdata:
@Entity(name="youtube_video_stat")
@Data
@EqualsAndHashCode(callSuper=true)
publicclassYoutubeVideoStatisticsextendsBaseEntity{
@Column(name="like_count")
privatelonglikeCount;
@Column(name="dislike_count")
privatelongdislikeCount;
@Column(name="view_count")
privatelongviewCount;
@Column(name="favourite_count")
privatelongfavouriteCount;
@Column(name="comment_count")
privatelongcommentCount;
@Column(name="video_id")
privateStringvideoId;
}
Andforcommonvideoproperties,wewillcollectthefollowingdata:
@Entity(name="youtube_video_info")
@Data
@EqualsAndHashCode(callSuper=true)
publicclassYouTubeVideoInfoextendsBaseEntity{
@Column(name="video_id")
privateStringvideoId;
@Column(name="title")
privateStringtitle;
@Column(name="thumbnail_url")
privateStringthumbnailUrl;
@Column(name="description")
privateStringdescription;
@Column(name="published_date")
privateDatepublishedDate;
@Column(name="definition")
privateStringvideoDefinition;
@Column(name="duration")
privateStringvideoDuration;
@Column(name="caption")
privateStringvideoCaption;
@Column(name="projection")
privateStringvideoprojection;
@Column(name="country_restricted")
privateStringcountryRestricted;
@Column(name="keyword")
privateStringkeyword;
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="channel_id",referencedColumnName="channel_id")
privateYoutubeChannelInfochannelInfo;
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="video_stat_id",referencedColumnName="video_id")
privateYoutubeVideoStatisticsvideoStatistics;
}
Now,wewillfetchvideoinformationthroughtheYouTubeDataAPI.So,weneedsomelibrariesprovidedbytheGoogleteam.
compilegroup:'com.google.api-client',name:'google-api-client',version:'1.25.0'
compilegroup:'com.google.apis',name:'google-api-services-youtube',version:'v3-rev212-1.25.0'
compilegroup:'com.google.apis',name:'google-api-services-youtubeAnalytics',version:'v1-rev14-1.13.2-beta'
compilegroup:'com.google.apis',name:'google-api-services-youtubereporting',version:'v1-rev1-1.20.0'
compile("com.google.oauth-client:google-oauth-client-jetty:1.25.0"){
excludegroup:'org.mortbay.jetty',module:'servlet-api'
}
compilegroup:'com.google.http-client',name:'google-http-client-jackson2',version:'1.25.0'
compilegroup:'com.google.collections',name:'google-collections',version:'1.0'
OtherlibrariesarealsousedforSpringBootanddatabasesupport.Wecanfindtheselibrariesat gradlefile .
Atfirst,wehavetoinitialize YouTube(v3)propertieswhichsupportscoreYouTubefeaturessuchasuploadingvideos,creatingandmanagingplaylists,searchingforcontent,andmuchmore.Buthere,wewillfirstimplementsomebasicproperties.
youtube=newYouTube.Builder(HTTP_TRANSPORT,JSON_FACTORY,newHttpRequestInitializer(){
publicvoidinitialize(HttpRequestrequest)throwsIOException{
}
}).setApplicationName("YoutubeVideoInfo")
.setYouTubeRequestInitializer
(newYouTubeRequestInitializer(env.getProperty("youtube.apikey"))).build();
WhenIwascreatingmycredentials,Ihadtocreateanapplicationname YouTubeVideoInfo thatisassignedasapplicationname.Thepropertyyoutube.apikeyislocatedintheapplication.propertiesfile.Wehavetoreplaceyoutube.apikey'svaluewithourones.
Now,wewillfetchsomeinformationusingthis.Initially,weuseid,snippet tofetchsomebasicdata.
YouTube.Search.Listsearch=youtube.search().list("id,snippet");
//searchkeywordeg."IELTS"
search.setQ(queryTerm);
//returnonlyvideotypedata
search.setType("video");
//numberofvideodatareturn.maximum50
search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
Here, queryTerm willbeoursearchkey,and video willbethedatatype sothatitwillreturnvideotypedatainformation.InayoutubeAPIlistrequest,maximum50videosinformationreturnsasresponse.
SearchListResponsesearchResponse=search.execute();
List
延伸文章資訊
- 1Java Quickstart | YouTube Data API - Google Developers
Java Quickstart · You will use an API key, which identifies your application, to retrieve informa...
- 2youtube/api-samples - GitHub
Code samples for YouTube APIs, including the YouTube Data API, YouTube Analytics API, and YouTube...
- 3YouTube Data API (v3): Introduction With Spring Boot - DZone
Java YouTube Data API. Learn more about app development using the YouTube Data API. YouTube is a ...
- 4YouTube Data API Client Library for Java - GitHub
- 5Java Sample Code examples youtube data api v3 and ...
If you look at Youtube Java sample code on Github, you can see that the search example is using a...