JavaScript Quickstart | YouTube Data API - Google Developers

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

This quickstart guide explains how to set up a simple page that makes requests to the YouTube Data API. This quickstart actually explains ... YouTube DataAPI English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어 Signin Home Guides Reference Samples Support YouTube DataAPI Home Guides Reference Samples Support Overview ClientLibraries AuthorizeRequests OverviewGetAuthCredentialsServer-sideWebAppsClient-sideWebAppsInstalledAppsDevices Quickstarts AndroidAppsScriptGoiOSJavaJavaScriptNode.jsPHPPythonRuby GuidesandTutorials QuotacostsforAPIrequestsQuotaandComplianceAuditsUploadaVideoSendResumableUploadsFindMadeForKidsvideostatusSubscribetoPushNotificationsWorkwithChannelIDsMovefromClientLogintoOAuth SampleRequests ImplementationGuide OverviewActivitiesCaptionsChannelsCommentsPaginationPartialresponsesPlaylistsRatingsSearchrequestsSubscriptionsVideos Tools APIsExplorer Home Products YouTube DataAPI Guides JavaScriptQuickstart Thisquickstartguideexplainshowtosetupasimplepagethatmakesrequests totheYouTubeDataAPI.ThisquickstartactuallyexplainshowtomaketwoAPI requests: YouwilluseanAPIkey,whichidentifiesyourapplication,to retrieveinformationabouttheGoogleDevelopersYouTubechannel. YouwilluseanOAuth2.0clientIDtosubmitanauthorizedrequest thatretrievesinformationaboutyourownYouTubechannel. Note:Moregenerally,youcanfollowtheinstructionsforthefirstexample foranyusecasethatusesanAPIkeyortheinstructionsforthesecond exampleforanyusecasethatrequiresauthorizationusingOAuth2.0.Seethe usecasesandcodesamplestoolfor moreexamples. Prerequisites Torunthisquickstart,you'llneed: Python2.4orgreater(toprovideawebserver) Accesstotheinternetandawebbrowser. AGoogleaccount. Step1:Setupyourprojectandcredentials CreateorselectaprojectintheAPIConsole.CompletethefollowingtasksintheAPIConsoleforyourproject: Inthelibrarypanel, searchfortheYouTubeDataAPIv3.ClickintothelistingforthatAPIand makesuretheAPIisenabledforyourproject. Inthecredentials panel, createtwocredentials: CreateanAPIkey YouwillusetheAPIkeytomakeAPIrequeststhatdo notrequireuserauthorization.Forexample,youdonotneeduser authorizationtoretrieveinformationaboutapublicYouTubechannel. CreateanOAuth2.0clientID SettheapplicationtypetoWebapplication.YouneedtouseOAuth 2.0credentialsforrequeststhatrequireuserauthorization.For example,youneeduserauthorizationtoretrieveinformationaboutthe currentlyauthenticateduser'sYouTubechannel. IntheAuthorizedJavaScriptoriginsfield,entertheURL http://localhost:8000.YoucanleavetheAuthorizedredirectURIs fieldblank. Step2:Setupandrunthesample UsetheAPIsExplorerwidgetinthesidepaneltoobtainsamplecodefor retrievinginformationabouttheGoogleDevelopersYouTubechannel.Thisrequest usesanAPIkeytoidentifyyourapplication,anditdoesnotrequireuser authorizationoranyspecialpermissionsfromtheuserrunningthesample. OpenthedocumentationfortheAPI's channels.listmethod. Onthatpage,the"Commonusecases"sectioncontainsatablethatexplains severalcommonwaysthatthemethodisused.Thefirstlistinginthetable isforlistingresultsbychannelID. Clickthecodesymbolforthefirstlistingtoopenandpopulatethe fullscreenAPIsExplorer. TheleftsideofthefullscreenAPIsExplorershowsthefollowing: BelowtheRequestparametersheader,thereisalistofparameters thatthemethodsupports.Thepartandidparametervaluesshould beset.Theidparametervalue,UC_x5XG1OV2P6uZZ5FSM9Ttw,isthe IDfortheGoogleDevelopersYouTubechannel. Belowtheparameters,thereisasectionnamedCredentials.The pulldownmenuinthatsectionshoulddisplaythevalueAPIkey.The APIsExplorerusesdemocredentialsbydefaulttomakeiteasiertoget started.Butyou'lluseyourownAPIkeytorunthesamplelocally. TherightsideofthefullscreenAPIsExplorershowstabswithcodesamples indifferentlanguages.SelecttheJavaScripttab. Copythecodesampleandsaveitinafilenamed example.html. Inthesamplethatyoudownloaded,findtheYOUR_API_KEYstringand replacethatwiththeAPIkeythatyoucreatedinstep1ofthisquickstart. Startthewebserverusingthefollowingcommandfromyourworking directory: Python2.x python-mSimpleHTTPServer8000 Python3.x python-mhttp.server8000 Opentheexample.htmlfileinyourbrowser.Alsoopenthebrowser's developertools,suchasthe"DeveloperTools"intheChromebrowser. ClicktheloadbuttononthepagetoloadtheGoogleAPIsClient LibraryforJavaScript.Afteryouclickthebutton,thedeveloper consoleshoulddisplayanoteindicatingthattheGAPIclientloaded. ClicktheexecutebuttontosendtheAPIrequest.Thedeveloper's consoleshouldthendisplaytheAPIresponse. Step3:Runanauthorizedrequest Inthisstep,you'llmodifyyourcodesamplesothatinsteadofretrieving informationabouttheGoogleDevelopersYouTubechannel,itretrievesinformation aboutyourYouTubechannel.Thisrequestdoesrequireuserauthorization. GobacktothedocumentationfortheAPI's channels.listmethod. Inthe"Commonusecases"section,clickthecodesymbolforthethird listinginthetable.Thatusecaseistocallthelistmethodfor"my channel." Again,intheleftsideofthefullscreenAPIsExplorer,youwillseea listofparametersfollowedbytheCredentialssection.However,there aretwochangesfromtheexamplewhereyouretrievedinformationaboutthe GoogleDeveloperschannel: Intheparameterssection,insteadoftheidparametervaluebeing set,themineparametervalueshouldbesettotrue.Thisinstructs theAPIservertoretrieveinformationaboutthecurrentlyauthenticated user'schannel. IntheCredentialssection,thepulldownmenushouldselectthe optionforGoogleOAuth2.0. Inaddition,ifyouclicktheShowscopeslink,the https://www.googleapis.com/auth/youtube.readonlyscopeshouldbe checked. Aswiththepreviousexample,selecttheJavaScripttab, copythecodesample,andsaveittoexample.html. Inthecode,findtheYOUR_CLIENT_IDstringandreplaceitwiththe clientIDthatyoucreatedinstep1ofthisquickstart. Startthewebserverusingthefollowingcommandfromyourworking directory: Python2.x python-mSimpleHTTPServer8000 Python3.x python-mhttp.server8000 Gotohttp://localhost:8000/example.htmlfileinyourbrowser. Openthebrowser'sdevelopertools,suchasthe"DeveloperTools"inthe Chromebrowser. ClicktheauthorizeandloadbuttononthepagetoloadtheGoogle APIsClientLibraryforJavaScriptandinitiatetheauthorizationflow. Youshouldbepromptedtogranttheapplicationpermissiontoreaddata fromyourYouTubeaccount. Ifyougrantthepermission,thedeveloper'sconsoleshoulddisplay messagesindicatingthatsign-inwassuccessfulandthattheAPIclient loaded. ClicktheexecutebuttontosendtheAPIrequest.Thedeveloper's consoleshouldthendisplaytheAPIresponse. Furtherreading GoogleDevelopersConsolehelpdocumentation GoogleAPIsClientLibraryforJavaScriptdocumentation YouTubeDataAPIreferencedocumentation Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2019-06-11UTC. [{ "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 English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어



請為這篇文章評分?