YouTube Data API (v3): Introduction With Spring Boot - DZone

文章推薦指數: 80 %
投票人數:10人

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(); ListsearchResultList=searchResponse.getItems(); if(searchResultList!=null){ extractAndSave(searchResultList.iterator(),queryTerm); } crawlingInfo.setNextPageToken(searchResponse.getNextPageToken()); crawlingInfoService.update(crawlingInfo); System.out.println("NextPagetoken:"+searchResponse.getNextPageToken()); Here, the search.execute() methodwillreturntheexpectedresult.So,wehavetoparsethisresponse.Andanotherthing:  CrawlingInfo classwillbeusedtomaintainthenextandpreviouspage.TheYouTubeAPIreturnsamaximumof50piecesofdatainarequestwiththenextpagetoken.Ifwewanttoaccessnextpagewehavetoadd nextPageToken atpageToken propertiesonrequest,thenitwillmovetothenextpage.That'swhywearekeepingthistrackusing crawlingInfo  entity. Wewillusemorequeriesontheremainingcodetoextractchannelinformation,contentdetails,statistics,etc.foreveryvideoandthensavetothedatabase. publicListgetYoutubeVideoList(StringqueryTerm,longpageToCrawl){ try{ youtube=newYouTube.Builder(HTTP_TRANSPORT,JSON_FACTORY,newHttpRequestInitializer(){ publicvoidinitialize(HttpRequestrequest)throwsIOException{ } }).setApplicationName("YoutubeVideoInfo") .setYouTubeRequestInitializer(newYouTubeRequestInitializer(env.getProperty("youtube.apikey"))).build(); YouTube.Search.Listsearch=youtube.search().list("id,snippet"); search.setQ(queryTerm); search.setType("video"); search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); for(inti=0;isearchResultList=searchResponse.getItems(); if(searchResultList!=null){ extractAndSave(searchResultList.iterator(),queryTerm); } crawlingInfo.setNextPageToken(searchResponse.getNextPageToken()); crawlingInfoService.update(crawlingInfo); System.out.println("NextPagetoken:"+searchResponse.getNextPageToken()); } }catch(GoogleJsonResponseExceptione){ System.err.println("Therewasaserviceerror:"+e.getDetails().getCode()+":" +e.getDetails().getMessage()); }catch(IOExceptione){ System.err.println("TherewasanIOerror:"+e.getCause()+":"+e.getMessage()); }catch(Throwablet){ t.printStackTrace(); } returnnull; } privatevoidextractAndSave(IteratoriteratorSearchResults,Stringquery)throwsIOException{ if(!iteratorSearchResults.hasNext()){ System.out.println("Therearen'tanyresultsforyourquery."); } while(iteratorSearchResults.hasNext()){ SearchResultsingleVideo=iteratorSearchResults.next(); System.out.println("Videonumber="+count+"InsertingvideoInformation"+singleVideo.getId().getVideoId()); count++; YouTubeVideoInfoyouTubeVideoInfo=youtubeVideoInfoService.getByVideoId(singleVideo.getId().getVideoId()); if(youTubeVideoInfo==null){ youTubeVideoInfo=newYouTubeVideoInfo(); ResourceIdrId=singleVideo.getId(); youTubeVideoInfo.setKeyword(query); youTubeVideoInfo.setDescription(singleVideo.getSnippet().getDescription()); youTubeVideoInfo.setPublishedDate(newDate(singleVideo.getSnippet().getPublishedAt().getValue())); if(rId.getKind().equals("youtube#video")){ Thumbnailthumbnail=singleVideo.getSnippet().getThumbnails().getDefault(); youTubeVideoInfo.setVideoId(rId.getVideoId()); youTubeVideoInfo.setTitle(singleVideo.getSnippet().getTitle()); youTubeVideoInfo.setThumbnailUrl(thumbnail.getUrl()); youTubeVideoInfo.setChannelInfo(getChannelDetailsById(singleVideo.getSnippet().getChannelId())); youTubeVideoInfo.setVideoStatistics(getVideosStatistics(rId.getVideoId())); } youtubeVideoInfoService.save(youTubeVideoInfo); }else{ System.out.println("VideoAlreadyexists..."); } } } privateYoutubeChannelInfogetChannelDetailsById(StringchannelId)throwsIOException{ YouTube.Channels.Listchannels=youtube.channels().list("snippet,statistics"); YoutubeChannelInfoyoutubeChannelInfo=newYoutubeChannelInfo(); youtubeChannelInfo.setChannelId(channelId); channels.setId(channelId); ChannelListResponsechannelResponse=channels.execute(); Channelc=channelResponse.getItems().get(0); youtubeChannelInfo.setName(c.getSnippet().getTitle()); youtubeChannelInfo.setSubscriptionCount(c.getStatistics().getSubscriberCount().longValue()); YoutubeChannelInfochannelInfo=youtubeChannelService.getByChannelId(channelId); if(channelInfo==null){ youtubeChannelService.save(youtubeChannelInfo); }else{ returnchannelInfo; } returnyoutubeChannelInfo; } publicYoutubeVideoStatisticsgetVideosStatistics(Stringid)throwsIOException{ YouTube.Videos.Listlist=youtube.videos().list("statistics"); list.setId(id); Videov=list.execute().getItems().get(0); YoutubeVideoStatisticsstatistics=newYoutubeVideoStatistics(); statistics.setVideoId(id); statistics.setLikeCount(v.getStatistics().getLikeCount()!=null?v.getStatistics().getLikeCount().longValue():0); statistics.setDislikeCount(v.getStatistics().getDislikeCount()!=null?v.getStatistics().getDislikeCount().longValue():0); statistics.setFavouriteCount(v.getStatistics().getFavoriteCount()!=null?v.getStatistics().getFavoriteCount().longValue():0); statistics.setCommentCount(v.getStatistics().getCommentCount()!=null?v.getStatistics().getCommentCount().longValue():0); statistics.setViewCount(v.getStatistics().getViewCount()!=null?v.getStatistics().getViewCount().longValue():0); youtubeVideoStatService.save(statistics); returnstatistics; } publicYouTubeVideoInfogetCoontentDetails(Stringid,YouTubeVideoInfoyouTubeVideoInfo)throwsIOException{ YouTube.Videos.Listlist=youtube.videos().list("contentDetails"); list.setId(id); Videov=list.execute().getItems().get(0); youTubeVideoInfo.setVideoDefinition(v.getContentDetails().getDefinition()); youTubeVideoInfo.setVideoCaption(v.getContentDetails().getCaption()); youTubeVideoInfo.setVideoprojection(v.getContentDetails().getProjection()); youTubeVideoInfo.setCountryRestricted(v.getContentDetails().getCountryRestriction().toPrettyString()); returnyouTubeVideoInfo; } Ifwetakealookonthepreviouscodesnippet,wecanseethat, for statistics and contentDetails,weareusingvideosresourcesandlistoperation.Andforchannelinformation,weareusingchannelresourcesandlistoperation.Here,IhaverepresentedalllistoperationsoftheYouTubeDataAPI.Andwithsimilar approach,wecanuseotheroperationssmoothly. Thecodeexamplesfromthisarticleareavailable here.  FurtherReading BuildaSpringBootAPIUsingSpringDataJPAandHibernate GettingStartedWithYouTubeJavaAPI API SpringFramework Data(computing) SpringBoot OpinionsexpressedbyDZonecontributorsaretheirown. PopularonDZone ChoosingtheBestKubernetesClusterandApplicationDeploymentStrategies Top11CloudPlatformsforInternetofThings(IoT) ComposableArchitecture WhatIsSmokeTesting?-ABriefGuide Comments JavaPartnerResources X



請為這篇文章評分?