Search: list | YouTube Data API - Google Developers

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

Search: list ... Returns a collection of search results that match the query parameters specified in the API request. By default, a search result set identifies ... YouTube DataAPI Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어 Signin Home Guides Reference Samples Support YouTube DataAPI Home Guides Reference Samples Support Overview Activities Overviewlistinsert Captions Overviewlistinsertupdatedownloaddelete ChannelBanners Overviewinsert Channels Overviewlistupdate ChannelSections Overviewlistinsertupdatedelete Comments OverviewlistinsertupdatemarkAsSpamsetModerationStatusdelete CommentThreads Overviewlistinsert i18nLanguages Overviewlist i18nRegions Overviewlist Members Overviewlist MembershipsLevels Overviewlist PlaylistItems Overviewlistinsertupdatedelete Playlists Overviewlistinsertupdatedelete Search Overviewlist Subscriptions Overviewlistinsertdelete Thumbnails Overviewset VideoAbuseReportReasons Overviewlist VideoCategories Overviewlist Videos OverviewlistinsertupdaterategetRatingreportAbusedelete Watermarks Overviewsetunset GuideCategories Overviewlist StandardQueryParameters YouTubeDataAPIErrors OverviewGlobalDomainErrors Home Products YouTube DataAPI Reference Search:list ReturnsacollectionofsearchresultsthatmatchthequeryparametersspecifiedintheAPIrequest.Bydefault,asearchresultsetidentifiesmatchingvideo,channel,andplaylistresources,butyoucanalsoconfigurequeriestoonlyretrieveaspecifictypeofresource. Quotaimpact:Acalltothismethodhasaquotacostof100units. Commonusecases Request HTTPrequest GEThttps://www.googleapis.com/youtube/v3/search Parameters Thefollowingtableliststheparametersthatthisquerysupports.Alloftheparameterslistedarequeryparameters. Parameters Requiredparameters part string Thepartparameterspecifiesacomma-separatedlistofoneormoresearchresourcepropertiesthattheAPIresponsewillinclude.Settheparametervaluetosnippet. Filters(specify0or1ofthefollowingparameters) forContentOwner boolean Thisparametercanonlybeusedinaproperlyauthorizedrequest,anditisintendedexclusivelyforYouTubecontentpartners.TheforContentOwnerparameterrestrictsthesearchtoonlyretrievevideosownedbythecontentowneridentifiedbytheonBehalfOfContentOwnerparameter.IfforContentOwnerissettotrue,therequestmustalsomeettheserequirements:TheonBehalfOfContentOwnerparameterisrequired.Theuserauthorizingtherequestmustbeusinganaccountlinkedtothespecifiedcontentowner.Thetypeparametervaluemustbesettovideo.Noneofthefollowingotherparameterscanbeset:videoDefinition,videoDimension,videoDuration,videoLicense,videoEmbeddable,videoSyndicated,videoType. forDeveloper boolean Thisparametercanonlybeusedinaproperlyauthorizedrequest.TheforDeveloperparameterrestrictsthesearchtoonlyretrievevideosuploadedviathedeveloper'sapplicationorwebsite.TheAPIserverusestherequest'sauthorizationcredentialstoidentifythedeveloper.TheforDeveloperparametercanbeusedinconjunctionwithoptionalsearchparametersliketheqparameter.Forthisfeature,eachuploadedvideoisautomaticallytaggedwiththeprojectnumberthatisassociatedwiththedeveloper'sapplicationintheGoogleDevelopersConsole.WhenasearchrequestsubsequentlysetstheforDeveloperparametertotrue,theAPIserverusestherequest'sauthorizationcredentialstoidentifythedeveloper.Therefore,adevelopercanrestrictresultstovideosuploadedthroughthedeveloper'sownapporwebsitebutnottovideosuploadedthroughotherappsorsites. forMine boolean Thisparametercanonlybeusedinaproperlyauthorizedrequest.TheforMineparameterrestrictsthesearchtoonlyretrievevideosownedbytheauthenticateduser.Ifyousetthisparametertotrue,thenthetypeparameter'svaluemustalsobesettovideo.Inaddition,noneofthefollowingotherparameterscanbesetinthesamerequest:videoDefinition,videoDimension,videoDuration,videoLicense,videoEmbeddable,videoSyndicated,videoType. relatedToVideoId string TherelatedToVideoIdparameterretrievesalistofvideosthatarerelatedtothevideothattheparametervalueidentifies.TheparametervaluemustbesettoaYouTubevideoIDand,ifyouareusingthisparameter,thetypeparametermustbesettovideo.NotethatiftherelatedToVideoIdparameterisset,theonlyothersupportedparametersarepart,maxResults,pageToken,regionCode,relevanceLanguage,safeSearch,type(whichmustbesettovideo),andfields. Optionalparameters channelId string ThechannelIdparameterindicatesthattheAPIresponseshouldonlycontainresourcescreatedbythechannel.Note:Searchresultsareconstrainedtoamaximumof500videosifyourrequestspecifiesavalueforthechannelIdparameterandsetsthetypeparametervaluetovideo,butitdoesnotalsosetoneoftheforContentOwner,forDeveloper,orforMinefilters. channelType string ThechannelTypeparameterletsyourestrictasearchtoaparticulartypeofchannel.Acceptablevaluesare: any–Returnallchannels. show–Onlyretrieveshows. eventType string TheeventTypeparameterrestrictsasearchtobroadcastevents.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo.Acceptablevaluesare: completed–Onlyincludecompletedbroadcasts. live–Onlyincludeactivebroadcasts. upcoming–Onlyincludeupcomingbroadcasts. location string Thelocationparameter,inconjunctionwiththelocationRadiusparameter,definesacirculargeographicareaandalsorestrictsasearchtovideosthatspecify,intheirmetadata,ageographiclocationthatfallswithinthatarea.Theparametervalueisastringthatspecifieslatitude/longitudecoordinatese.g.(37.42307,-122.08427).Thelocationparametervalueidentifiesthepointatthecenterofthearea.ThelocationRadiusparameterspecifiesthemaximumdistancethatthelocationassociatedwithavideocanbefromthatpointforthevideotostillbeincludedinthesearchresults.TheAPIreturnsanerrorifyourrequestspecifiesavalueforthelocationparameterbutdoesnotalsospecifyavalueforthelocationRadiusparameter.Note:Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo. locationRadius string ThelocationRadiusparameter,inconjunctionwiththelocationparameter,definesacirculargeographicarea.Theparametervaluemustbeafloatingpointnumberfollowedbyameasurementunit.Validmeasurementunitsarem,km,ft,andmi.Forexample,validparametervaluesinclude1500m,5km,10000ft,and0.75mi.TheAPIdoesnotsupportlocationRadiusparametervalueslargerthan1000kilometers.Note:Seethedefinitionofthelocationparameterformoreinformation. maxResults unsignedinteger ThemaxResultsparameterspecifiesthemaximumnumberofitemsthatshouldbereturnedintheresultset.Acceptablevaluesare0to50,inclusive.Thedefaultvalueis5. onBehalfOfContentOwner string Thisparametercanonlybeusedinaproperlyauthorizedrequest.Note:ThisparameterisintendedexclusivelyforYouTubecontentpartners.TheonBehalfOfContentOwnerparameterindicatesthattherequest'sauthorizationcredentialsidentifyaYouTubeCMSuserwhoisactingonbehalfofthecontentownerspecifiedintheparametervalue.ThisparameterisintendedforYouTubecontentpartnersthatownandmanagemanydifferentYouTubechannels.Itallowscontentownerstoauthenticateonceandgetaccesstoalltheirvideoandchanneldata,withouthavingtoprovideauthenticationcredentialsforeachindividualchannel.TheCMSaccountthattheuserauthenticateswithmustbelinkedtothespecifiedYouTubecontentowner. order string TheorderparameterspecifiesthemethodthatwillbeusedtoorderresourcesintheAPIresponse.Thedefaultvalueisrelevance.Acceptablevaluesare: date–Resourcesaresortedinreversechronologicalorderbasedonthedatetheywerecreated. rating–Resourcesaresortedfromhighesttolowestrating. relevance–Resourcesaresortedbasedontheirrelevancetothesearchquery.Thisisthedefaultvalueforthisparameter. title–Resourcesaresortedalphabeticallybytitle. videoCount–Channelsaresortedindescendingorderoftheirnumberofuploadedvideos. viewCount–Resourcesaresortedfromhighesttolowestnumberofviews.Forlivebroadcasts,videosaresortedbynumberofconcurrentviewerswhilethebroadcastsareongoing. pageToken string ThepageTokenparameteridentifiesaspecificpageintheresultsetthatshouldbereturned.InanAPIresponse,thenextPageTokenandprevPageTokenpropertiesidentifyotherpagesthatcouldberetrieved. publishedAfter datetime ThepublishedAfterparameterindicatesthattheAPIresponseshouldonlycontainresourcescreatedatorafterthespecifiedtime.ThevalueisanRFC3339formatteddate-timevalue(1970-01-01T00:00:00Z). publishedBefore datetime ThepublishedBeforeparameterindicatesthattheAPIresponseshouldonlycontainresourcescreatedbeforeoratthespecifiedtime.ThevalueisanRFC3339formatteddate-timevalue(1970-01-01T00:00:00Z). q string Theqparameterspecifiesthequerytermtosearchfor.YourrequestcanalsousetheBooleanNOT(-)andOR(|)operatorstoexcludevideosortofindvideosthatareassociatedwithoneofseveralsearchterms.Forexample,tosearchforvideosmatchingeither"boating"or"sailing",settheqparametervaluetoboating|sailing.Similarly,tosearchforvideosmatchingeither"boating"or"sailing"butnot"fishing",settheqparametervaluetoboating|sailing-fishing.NotethatthepipecharactermustbeURL-escapedwhenitissentinyourAPIrequest.TheURL-escapedvalueforthepipecharacteris%7C. regionCode string TheregionCodeparameterinstructstheAPItoreturnsearchresultsforvideosthatcanbeviewedinthespecifiedcountry.TheparametervalueisanISO3166-1alpha-2countrycode. relevanceLanguage string TherelevanceLanguageparameterinstructstheAPItoreturnsearchresultsthataremostrelevanttothespecifiedlanguage.TheparametervalueistypicallyanISO639-1two-letterlanguagecode.However,youshouldusethevalueszh-HansforsimplifiedChineseandzh-HantfortraditionalChinese.Pleasenotethatresultsinotherlanguageswillstillbereturnediftheyarehighlyrelevanttothesearchqueryterm. safeSearch string ThesafeSearchparameterindicateswhetherthesearchresultsshouldincluderestrictedcontentaswellasstandardcontent.Acceptablevaluesare: moderate–YouTubewillfiltersomecontentfromsearchresultsand,attheleast,willfiltercontentthatisrestrictedinyourlocale.Basedontheircontent,searchresultscouldberemovedfromsearchresultsordemotedinsearchresults.Thisisthedefaultparametervalue. none–YouTubewillnotfilterthesearchresultset. strict–YouTubewilltrytoexcludeallrestrictedcontentfromthesearchresultset.Basedontheircontent,searchresultscouldberemovedfromsearchresultsordemotedinsearchresults. topicId string ThetopicIdparameterindicatesthattheAPIresponseshouldonlycontainresourcesassociatedwiththespecifiedtopic.ThevalueidentifiesaFreebasetopicID.Important:DuetothedeprecationofFreebaseandtheFreebaseAPI,thetopicIdparameterstartedworkingdifferentlyasofFebruary27,2017.Atthattime,YouTubestartedsupportingasmallsetofcuratedtopicIDs,andyoucanonlyusethatsmallersetofIDsasvaluesforthisparameter. SeetopicIDssupportedasofFebruary15,2017 Topics Musictopics /m/04rlf Music(parenttopic) /m/02mscn Christianmusic /m/0ggq0m Classicalmusic /m/01lyv Country /m/02lkt Electronicmusic /m/0glt670 Hiphopmusic /m/05rwpb Independentmusic /m/03_d0 Jazz /m/028sqc MusicofAsia /m/0g293 MusicofLatinAmerica /m/064t9 Popmusic /m/06cqb Reggae /m/06j6l Rhythmandblues /m/06by7 Rockmusic /m/0gywn Soulmusic Gamingtopics /m/0bzvm2 Gaming(parenttopic) /m/025zzc Actiongame /m/02ntfj Action-adventuregame /m/0b1vjn Casualgame /m/02hygl Musicvideogame /m/04q1x3q Puzzlevideogame /m/01sjng Racingvideogame /m/0403l3g Role-playingvideogame /m/021bp2 Simulationvideogame /m/022dc6 Sportsgame /m/03hf_rm Strategyvideogame Sportstopics /m/06ntj Sports(parenttopic) /m/0jm_ Americanfootball /m/018jz Baseball /m/018w8 Basketball /m/01cgz Boxing /m/09xp_ Cricket /m/02vx4 Football /m/037hz Golf /m/03tmr Icehockey /m/01h7lh Mixedmartialarts /m/0410tth Motorsport /m/07bs0 Tennis /m/07_53 Volleyball Entertainmenttopics /m/02jjt Entertainment(parenttopic) /m/09kqc Humor /m/02vxn Movies /m/05qjc Performingarts /m/066wd Professionalwrestling /m/0f2f9 TVshows Lifestyletopics /m/019_rr Lifestyle(parenttopic) /m/032tl Fashion /m/027x7n Fitness /m/02wbm Food /m/03glg Hobby /m/068hy Pets /m/041xxh Physicalattractiveness[Beauty] /m/07c1v Technology /m/07bxq Tourism /m/07yv9 Vehicles Societytopics /m/098wr Society(parenttopic) /m/09s1f Business /m/0kt51 Health /m/01h6rj Military /m/05qt0 Politics /m/06bvp Religion Othertopics /m/01k8wb Knowledge type string Thetypeparameterrestrictsasearchquerytoonlyretrieveaparticulartypeofresource.Thevalueisacomma-separatedlistofresourcetypes.Thedefaultvalueisvideo,channel,playlist.Acceptablevaluesare: channelplaylistvideo videoCaption string ThevideoCaptionparameterindicateswhethertheAPIshouldfiltervideosearchresultsbasedonwhethertheyhavecaptions.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo.Acceptablevaluesare: any–Donotfilterresultsbasedoncaptionavailability. closedCaption–Onlyincludevideosthathavecaptions. none–Onlyincludevideosthatdonothavecaptions. videoCategoryId string ThevideoCategoryIdparameterfiltersvideosearchresultsbasedontheircategory.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo. videoDefinition string ThevideoDefinitionparameterletsyourestrictasearchtoonlyincludeeitherhighdefinition(HD)orstandarddefinition(SD)videos.HDvideosareavailableforplaybackinatleast720p,thoughhigherresolutions,like1080p,mightalsobeavailable.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo.Acceptablevaluesare: any–Returnallvideos,regardlessoftheirresolution. high–OnlyretrieveHDvideos. standard–Onlyretrievevideosinstandarddefinition. videoDimension string ThevideoDimensionparameterletsyourestrictasearchtoonlyretrieve2Dor3Dvideos.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo.Acceptablevaluesare: 2d–Restrictsearchresultstoexclude3Dvideos. 3d–Restrictsearchresultstoonlyinclude3Dvideos. any–Includeboth3Dandnon-3Dvideosinreturnedresults.Thisisthedefaultvalue. videoDuration string ThevideoDurationparameterfiltersvideosearchresultsbasedontheirduration.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo.Acceptablevaluesare: any–Donotfiltervideosearchresultsbasedontheirduration.Thisisthedefaultvalue. long–Onlyincludevideoslongerthan20minutes. medium–Onlyincludevideosthatarebetweenfourand20minuteslong(inclusive). short–Onlyincludevideosthatarelessthanfourminuteslong. videoEmbeddable string ThevideoEmbeddableparameterletsyoutorestrictasearchtoonlyvideosthatcanbeembeddedintoawebpage.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo.Acceptablevaluesare: any–Returnallvideos,embeddableornot. true–Onlyretrieveembeddablevideos. videoLicense string ThevideoLicenseparameterfilterssearchresultstoonlyincludevideoswithaparticularlicense.YouTubeletsvideouploaderschoosetoattacheithertheCreativeCommonslicenseorthestandardYouTubelicensetoeachoftheirvideos.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo.Acceptablevaluesare: any–Returnallvideos,regardlessofwhichlicensetheyhave,thatmatchthequeryparameters. creativeCommon–OnlyreturnvideosthathaveaCreativeCommonslicense.Userscanreusevideoswiththislicenseinothervideosthattheycreate.Learnmore. youtube–OnlyreturnvideosthathavethestandardYouTubelicense. videoSyndicated string ThevideoSyndicatedparameterletsyoutorestrictasearchtoonlyvideosthatcanbeplayedoutsideyoutube.com.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo.Acceptablevaluesare: any–Returnallvideos,syndicatedornot. true–Onlyretrievesyndicatedvideos. videoType string ThevideoTypeparameterletsyourestrictasearchtoaparticulartypeofvideos.Ifyouspecifyavalueforthisparameter,youmustalsosetthetypeparameter'svaluetovideo.Acceptablevaluesare: any–Returnallvideos. episode–Onlyretrieveepisodesofshows. movie–Onlyretrievemovies. Requestbody Donotprovidearequestbodywhencallingthismethod. Response Ifsuccessful,thismethodreturnsaresponsebodywiththefollowingstructure: { "kind":"youtube#searchListResponse", "etag":etag, "nextPageToken":string, "prevPageToken":string, "regionCode":string, "pageInfo":{ "totalResults":integer, "resultsPerPage":integer }, "items":[ searchResource ] } Properties Thefollowingtabledefinesthepropertiesthatappearinasearchresult: Properties kind string IdentifiestheAPIresource'stype.Thevaluewillbeyoutube#searchListResponse. etag etag TheEtagofthisresource. nextPageToken string ThetokenthatcanbeusedasthevalueofthepageTokenparametertoretrievethenextpageintheresultset. prevPageToken string ThetokenthatcanbeusedasthevalueofthepageTokenparametertoretrievethepreviouspageintheresultset. regionCode string Theregioncodethatwasusedforthesearchquery.Thepropertyvalueisatwo-letterISOcountrycodethatidentifiestheregion.Thei18nRegions.listmethodreturnsalistofsupportedregions.ThedefaultvalueisUS.Ifanon-supportedregionisspecified,YouTubemightstillselectanotherregion,ratherthanthedefaultvalue,tohandlethequery. pageInfo object ThepageInfoobjectencapsulatespaginginformationfortheresultset. pageInfo.totalResults integer Thetotalnumberofresultsintheresultset.Pleasenotethatthevalueisanapproximationandmaynotrepresentanexactvalue.Inaddition,themaximumvalueis1,000,000.Youshouldnotusethisvaluetocreatepaginationlinks.Instead,usethenextPageTokenandprevPageTokenpropertyvaluestodeterminewhethertoshowpaginationlinks. pageInfo.resultsPerPage integer ThenumberofresultsincludedintheAPIresponse. items[] list Alistofresultsthatmatchthesearchcriteria. Examples Note:Thefollowingcodesamplesmaynotrepresentallsupportedprogramminglanguages.Seetheclientlibrariesdocumentationforalistofsupportedlanguages. AppsScript Thisfunctionsearchesforvideosrelatedtothekeyword'dogs'.ThevideoIDsandtitlesofthesearchresultsareloggedtoAppsScript'slog.Notethatthissamplelimitstheresultsto25.Toreturnmoreresults,passadditionalparametersasdocumentedhere:https://developers.google.com/youtube/v3/docs/search/list functionsearchByKeyword(){ varresults=YouTube.Search.list('id,snippet',{q:'dogs',maxResults:25}); for(variinresults.items){ varitem=results.items[i]; Logger.log('[%s]Title:%s',item.id.videoId,item.snippet.title); } }youtube.gs Go ThiscodesamplecallstheAPI'ssearch.listmethodtoretrievesearchresultsassociated withaparticularkeyword. ThisexampleusestheGoclientlibrary. packagemain import( "flag" "fmt" "log" "net/http" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" ) var( query=flag.String("query","Google","Searchterm") maxResults=flag.Int64("max-results",25,"MaxYouTuberesults") ) constdeveloperKey="YOURDEVELOPERKEY" funcmain(){ flag.Parse() client:=&http.Client{ Transport:&transport.APIKey{Key:developerKey}, } service,err:=youtube.New(client) iferr!=nil{ log.Fatalf("ErrorcreatingnewYouTubeclient:%v",err) } //MaketheAPIcalltoYouTube. call:=service.Search.List("id,snippet"). Q(*query). MaxResults(*maxResults) response,err:=call.Do() handleError(err,"") //Groupvideo,channel,andplaylistresultsinseparatelists. videos:=make(map[string]string) channels:=make(map[string]string) playlists:=make(map[string]string) //Iteratethrougheachitemandaddittothecorrectlist. for_,item:=rangeresponse.Items{ switchitem.Id.Kind{ case"youtube#video": videos[item.Id.VideoId]=item.Snippet.Title case"youtube#channel": channels[item.Id.ChannelId]=item.Snippet.Title case"youtube#playlist": playlists[item.Id.PlaylistId]=item.Snippet.Title } } printIDs("Videos",videos) printIDs("Channels",channels) printIDs("Playlists",playlists) } //PrinttheIDandtitleofeachresultinalistaswellasanamethat //identifiesthelist.Forexample,printthewordsectionname"Videos" //abovealistofvideosearchresults,followedbythevideoIDandtitle //ofeachmatchingvideo. funcprintIDs(sectionNamestring,matchesmap[string]string){ fmt.Printf("%v:\n",sectionName) forid,title:=rangematches{ fmt.Printf("[%v]%v\n",id,title) } fmt.Printf("\n\n") } search_by_keyword.go .NET ThefollowingcodesamplecallstheAPI'ssearch.listmethodtoretrievesearchresults associatedwithaparticularkeyword. Thisexampleusesthe.NETclientlibrary. usingSystem; usingSystem.Collections.Generic; usingSystem.IO; usingSystem.Reflection; usingSystem.Threading; usingSystem.Threading.Tasks; usingGoogle.Apis.Auth.OAuth2; usingGoogle.Apis.Services; usingGoogle.Apis.Upload; usingGoogle.Apis.Util.Store; usingGoogle.Apis.YouTube.v3; usingGoogle.Apis.YouTube.v3.Data; namespaceGoogle.Apis.YouTube.Samples { ///

///YouTubeDataAPIv3sample:searchbykeyword. ///ReliesontheGoogleAPIsClientLibraryfor.NET,v1.7.0orhigher. ///Seehttps://developers.google.com/api-client-library/dotnet/get_started /// ///SetApiKeytotheAPIkeyvaluefromtheAPIs&auth>Registeredappstabof ///https://cloud.google.com/console ///PleaseensurethatyouhaveenabledtheYouTubeDataAPIforyourproject. /// internalclassSearch { [STAThread] staticvoidMain(string[]args) { Console.WriteLine("YouTubeDataAPI:Search"); Console.WriteLine("========================"); try { newSearch().Run().Wait(); } catch(AggregateExceptionex) { foreach(vareinex.InnerExceptions) { Console.WriteLine("Error:"+e.Message); } } Console.WriteLine("Pressanykeytocontinue..."); Console.ReadKey(); } privateasyncTaskRun() { varyoutubeService=newYouTubeService(newBaseClientService.Initializer() { ApiKey="REPLACE_ME", ApplicationName=this.GetType().ToString() }); varsearchListRequest=youtubeService.Search.List("snippet"); searchListRequest.Q="Google";//Replacewithyoursearchterm. searchListRequest.MaxResults=50; //Callthesearch.listmethodtoretrieveresultsmatchingthespecifiedqueryterm. varsearchListResponse=awaitsearchListRequest.ExecuteAsync(); Listvideos=newList(); Listchannels=newList(); Listplaylists=newList(); //Addeachresulttotheappropriatelist,andthendisplaythelistsof //matchingvideos,channels,andplaylists. foreach(varsearchResultinsearchListResponse.Items) { switch(searchResult.Id.Kind) { case"youtube#video": videos.Add(String.Format("{0}({1})",searchResult.Snippet.Title,searchResult.Id.VideoId)); break; case"youtube#channel": channels.Add(String.Format("{0}({1})",searchResult.Snippet.Title,searchResult.Id.ChannelId)); break; case"youtube#playlist": playlists.Add(String.Format("{0}({1})",searchResult.Snippet.Title,searchResult.Id.PlaylistId)); break; } } Console.WriteLine(String.Format("Videos:\n{0}\n",string.Join("\n",videos))); Console.WriteLine(String.Format("Channels:\n{0}\n",string.Join("\n",channels))); Console.WriteLine(String.Format("Playlists:\n{0}\n",string.Join("\n",playlists))); } } } Search.cs Ruby ThissamplecallstheAPI'ssearch.listmethodtoretrievesearchresults associatedwithaparticularkeyword. ThisexampleusestheRubyclientlibrary. #!/usr/bin/ruby require'rubygems' gem'google-api-client','>0.7' require'google/api_client' require'trollop' #SetDEVELOPER_KEYtotheAPIkeyvaluefromtheAPIs&auth>Credentials #tabof #{{GoogleCloudConsole}} #PleaseensurethatyouhaveenabledtheYouTubeDataAPIforyourproject. DEVELOPER_KEY='REPLACE_ME' YOUTUBE_API_SERVICE_NAME='youtube' YOUTUBE_API_VERSION='v3' defget_service client=Google::APIClient.new( :key=>DEVELOPER_KEY, :authorization=>nil, :application_name=>$PROGRAM_NAME, :application_version=>'1.0.0' ) youtube=client.discovered_api(YOUTUBE_API_SERVICE_NAME,YOUTUBE_API_VERSION) returnclient,youtube end defmain opts=Trollop::optionsdo opt:q,'Searchterm',:type=>String,:default=>'Google' opt:max_results,'Maxresults',:type=>:int,:default=>25 end client,youtube=get_service begin #Callthesearch.listmethodtoretrieveresultsmatchingthespecified #queryterm. search_response=client.execute!( :api_method=>youtube.search.list, :parameters=>{ :part=>'snippet', :q=>opts[:q], :maxResults=>opts[:max_results] } ) videos=[] channels=[] playlists=[] #Addeachresulttotheappropriatelist,andthendisplaythelistsof #matchingvideos,channels,andplaylists. search_response.data.items.eachdo|search_result| casesearch_result.id.kind when'youtube#video' videos<e putse.result.body end end main search.rb Errors ThefollowingtableidentifieserrormessagesthattheAPIcouldreturninresponsetoacalltothismethod.Pleaseseetheerrormessagedocumentationformoredetail. Errortype Errordetail Description badRequest(400) invalidChannelId ThechannelIdparameterspecifiedaninvalidchannelID. badRequest(400) invalidLocation Thelocationand/orlocationRadiusparametervaluewasformattedincorrectly. badRequest(400) invalidRelevanceLanguage TherelevanceLanguageparametervaluewasformattedincorrectly. badRequest(400) invalidSearchFilter Therequestcontainsaninvalidcombinationofsearchfiltersand/orrestrictions.NotethatyoumustsetthetypeparametertovideoifyouseteithertheforContentOwnerorforMineparameterstotrue.YoumustalsosetthetypeparametertovideoifyousetavaluefortheeventType,videoCaption,videoCategoryId,videoDefinition,videoDimension,videoDuration,videoEmbeddable,videoLicense,videoSyndicated,orvideoTypeparameters. badRequest(400) invalidVideoId TherelatedToVideoparameterspecifiedaninvalidvideoID. Tryit! UsetheAPIsExplorertocallthisAPIandseetheAPIrequestandresponse. Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2022-03-07UTC. [{ "type":"thumb-down", "id":"missingTheInformationINeed", "label":"MissingtheinformationIneed" },{ "type":"thumb-down", "id":"tooComplicatedTooManySteps", "label":"Toocomplicated/toomanysteps" },{ "type":"thumb-down", "id":"outOfDate", "label":"Outofdate" },{ "type":"thumb-down", "id":"samplesCodeIssue", "label":"Samples/codeissue" },{ "type":"thumb-down", "id":"otherDown", "label":"Other" }] [{ "type":"thumb-up", "id":"easyToUnderstand", "label":"Easytounderstand" },{ "type":"thumb-up", "id":"solvedMyProblem", "label":"Solvedmyproblem" },{ "type":"thumb-up", "id":"otherUp", "label":"Other" }] Blog ThelatestnewsontheYouTubeblog GitHub FindAPIcodesamplesandotherYouTubeopen-sourceprojects. IssueTracker Somethingwrong?Sendusabugreport! StackOverflow Askaquestionundertheyoutube-apitag Videos CheckouttheYouTubeDeveloperRelationsteam'sYouTubechannel Tools GoogleAPIsExplorer YouTubePlayerDemo ConfigureaSubscribeButton IssueTracker Fileabug Requestafeature Seeopenissues ProductInfo TermsofService BrandingGuidelines MonetizationGuidelines APIssubjecttoDeprecationPolicy Android Chrome Firebase GoogleCloudPlatform Allproducts Terms Privacy SignupfortheGoogleDevelopersnewsletter Subscribe Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어



請為這篇文章評分?