Koleksiyonlar ile düzeninizi koruyun
İçeriği tercihlerinize göre kaydedin ve kategorilere ayırın.
Bu sayfanın geri kalanında açıklanan adımları tamamladığınızda yaklaşık beş dakika içinde YouTube Data API'ye istek gönderen basit bir Go komut satırı uygulamasına sahip olursunuz.
Bu kılavuzda kullanılan örnek kod, GoogleDevelopers YouTube kanalının channel kaynağını alıp bu kaynaktan bazı temel bilgileri yazdırır.
Ön koşullar
Bu hızlı başlangıç kılavuzunu çalıştırmak için ihtiyacınız olanlar:
Google Developers Console'da proje oluşturmak veya seçmek ve API'yi otomatik olarak etkinleştirmek için bu sihirbazı kullanın. Devam'ı, ardından Kimlik bilgilerine git'i tıklayın.
Sayfanın üst kısmından OAuth izin ekranı sekmesini seçin.
Bir e-posta adresi seçin, henüz ayarlanmamışsa ürün adını girin ve Kaydet düğmesini tıklayın.
Kimlik bilgileri sekmesini seçin, Kimlik bilgisi oluştur düğmesini tıklayın ve OAuth istemci kimliği'ni seçin.
Diğer uygulama türünü seçin, "YouTube Data API Quickstart" adını girin ve Oluştur düğmesini tıklayın.
Sonuçta ortaya çıkan iletişim kutusunu kapatmak için Tamam'ı tıklayın.
İndirilen dosyayı çalışma dizininize taşıyın ve yeniden adlandırın
client_secret.json.
2. adım: Çalışma alanını hazırlayın
GOPATH ortam değişkenini çalışma dizininize ayarlayın.
Aşağıdaki komutları kullanarak YouTube Data API Go istemci kitaplığını ve OAuth2 paketini edinin:
go get -u google.golang.org/api/youtube/v3go get -u golang.org/x/oauth2/...
3. adım: Örnek oluşturun
Çalışma dizininizde quickstart.go adlı bir dosya oluşturun ve aşağıdaki kodu kopyalayın:
// Sample Go code for user authorizationpackagemainimport("encoding/json""fmt""log""io/ioutil""net/http""net/url""os""os/user""path/filepath""golang.org/x/net/context""golang.org/x/oauth2""golang.org/x/oauth2/google""google.golang.org/api/youtube/v3")constmissingClientSecretsMessage=`Please configure OAuth 2.0`// getClient uses a Context and Config to retrieve a Token// then generate a Client. It returns the generated Client.funcgetClient(ctxcontext.Context,config*oauth2.Config)*http.Client{cacheFile,err:=tokenCacheFile()iferr!=nil{log.Fatalf("Unable to get path to cached credential file. %v",err)}tok,err:=tokenFromFile(cacheFile)iferr!=nil{tok=getTokenFromWeb(config)saveToken(cacheFile,tok)}returnconfig.Client(ctx,tok)}// getTokenFromWeb uses Config to request a Token.// It returns the retrieved Token.funcgetTokenFromWeb(config*oauth2.Config)*oauth2.Token{authURL:=config.AuthCodeURL("state-token",oauth2.AccessTypeOffline)fmt.Printf("Go to the following link in your browser then type the "+"authorization code: \n%v\n",authURL)varcodestringif_,err:=fmt.Scan(&code);err!=nil{log.Fatalf("Unable to read authorization code %v",err)}tok,err:=config.Exchange(oauth2.NoContext,code)iferr!=nil{log.Fatalf("Unable to retrieve token from web %v",err)}returntok}// tokenCacheFile generates credential file path/filename.// It returns the generated credential path/filename.functokenCacheFile()(string,error){usr,err:=user.Current()iferr!=nil{return"",err}tokenCacheDir:=filepath.Join(usr.HomeDir,".credentials")os.MkdirAll(tokenCacheDir,0700)returnfilepath.Join(tokenCacheDir,url.QueryEscape("youtube-go-quickstart.json")),err}// tokenFromFile retrieves a Token from a given file path.// It returns the retrieved Token and any read error encountered.functokenFromFile(filestring)(*oauth2.Token,error){f,err:=os.Open(file)iferr!=nil{returnnil,err}t:=&oauth2.Token{}err=json.NewDecoder(f).Decode(t)deferf.Close()returnt,err}// saveToken uses a file path to create a file and store the// token in it.funcsaveToken(filestring,token*oauth2.Token){fmt.Printf("Saving credential file to: %s\n",file)f,err:=os.OpenFile(file,os.O_RDWR|os.O_CREATE|os.O_TRUNC,0600)iferr!=nil{log.Fatalf("Unable to cache oauth token: %v",err)}deferf.Close()json.NewEncoder(f).Encode(token)}funchandleError(errerror,messagestring){ifmessage==""{message="Error making API call"}iferr!=nil{log.Fatalf(message+": %v",err.Error())}}funcchannelsListByUsername(service*youtube.Service,partstring,forUsernamestring){call:=service.Channels.List(part)call=call.ForUsername(forUsername)response,err:=call.Do()handleError(err,"")fmt.Println(fmt.Sprintf("This channel's ID is %s. Its title is '%s', "+"and it has %d views.",response.Items[0].Id,response.Items[0].Snippet.Title,response.Items[0].Statistics.ViewCount))}funcmain(){ctx:=context.Background()b,err:=ioutil.ReadFile("client_secret.json")iferr!=nil{log.Fatalf("Unable to read client secret file: %v",err)}// If modifying these scopes, delete your previously saved credentials// at ~/.credentials/youtube-go-quickstart.jsonconfig,err:=google.ConfigFromJSON(b,youtube.YoutubeReadonlyScope)iferr!=nil{log.Fatalf("Unable to parse client secret file to config: %v",err)}client:=getClient(ctx,config)service,err:=youtube.New(client)handleError(err,"Error creating YouTube client")channelsListByUsername(service,"snippet,contentDetails,statistics","GoogleDevelopers")}
Çalışma dizininizden aşağıdaki komutu kullanarak örneği oluşturun ve çalıştırın:
go run quickstart.go
Örneği ilk kez çalıştırdığınızda erişimi yetkilendirmeniz istenir:
Web tarayıcınızda sağlanan URL'ye gidin.
Google Hesabınıza henüz giriş yapmadıysanız giriş yapmanız istenir. Birden fazla Google Hesabı'nda oturum açtıysanız yetkilendirme için kullanmak istediğiniz hesabı seçmeniz istenir.
Kabul et düğmesini tıklayın.
Size verilen kodu kopyalayın, komut satırı istemine yapıştırın ve Enter tuşuna basın.
Notlar
Yetkilendirme bilgileri dosya sisteminde depolandığından sonraki yürütmelerde yetkilendirme istenmez.
Bu örnekteki yetkilendirme akışı, komut satırı uygulaması için tasarlanmıştır. Web uygulamasında yetkilendirme işleminin nasıl yapılacağı hakkında bilgi edinmek için Web Sunucusu Uygulamaları için OAuth 2.0'ı Kullanma başlıklı makaleyi inceleyin.
[null,null,["Son güncelleme tarihi: 2025-08-21 UTC."],[[["\u003cp\u003eThis guide walks you through creating a simple Go command-line application that interacts with the YouTube Data API within about five minutes.\u003c/p\u003e\n"],["\u003cp\u003eThe application retrieves the \u003ccode\u003echannel\u003c/code\u003e resource for the GoogleDevelopers YouTube channel and outputs its ID, title, and view count.\u003c/p\u003e\n"],["\u003cp\u003ePrerequisites include the latest versions of Go and Git, a web browser, internet access, and a Google account.\u003c/p\u003e\n"],["\u003cp\u003eThe guide covers turning on the YouTube Data API, preparing the workspace by setting the \u003ccode\u003eGOPATH\u003c/code\u003e variable and getting necessary packages, and setting up the sample Go code.\u003c/p\u003e\n"],["\u003cp\u003eRunning the sample involves a one-time authorization process through a web browser, after which authorization information is stored for subsequent executions.\u003c/p\u003e\n"]]],["First, enable the YouTube Data API in the Google Developers Console and create OAuth credentials, downloading `client_secret.json`. Next, set the `GOPATH` environment variable and use `go get` to acquire the YouTube Data API Go client library and OAuth2 package. Create `quickstart.go` with the provided code. Then run the sample with `go run quickstart.go`. This prompts you to authorize access via a web browser. Finally, copy and paste the provided code into the command line to complete the authorization.\n"],null,["# Go Quickstart\n\nComplete the steps described in the rest of this page, and in about five minutes\nyou'll have a simple Go command-line application that makes requests to the\nYouTube Data API.\nThe sample code used in this guide retrieves the `channel` resource for the GoogleDevelopers YouTube channel and prints some basic information from that resource.\n\nPrerequisites\n-------------\n\nTo run this quickstart, you'll need:\n\n- [Go](https://golang.org/), latest version recommended.\n- [Git](https://git-scm.com/), latest version recommended.\n- Access to the internet and a web browser.\n- A Google account.\n\nStep 1: Turn on the YouTube Data API\n------------------------------------\n\n1. Use\n [this wizard](https://console.developers.google.com/start/api?id=youtube)\n to create or select a project in the Google Developers Console and\n automatically turn on the API. Click **Continue** , then\n **Go to credentials**.\n\n2. On the **Create credentials** page, click the\n **Cancel** button.\n\n3. At the top of the page, select the **OAuth consent screen** tab.\n Select an **Email address** , enter a **Product name** if not\n already set, and click the **Save** button.\n\n4. Select the **Credentials** tab, click the **Create credentials**\n button and select **OAuth client ID**.\n\n5. Select the application type **Other** , enter the name\n \"YouTube Data API Quickstart\", and click the **Create** button.\n\n6. Click **OK** to dismiss the resulting dialog.\n\n7. Click the file_download\n (Download JSON) button to the right of the client ID.\n\n8. Move the downloaded file to your working directory and rename it\n `client_secret.json`.\n\nStep 2: Prepare the workspace\n-----------------------------\n\n1. Set the `GOPATH` environment variable to your working directory.\n2. Get the YouTube Data API Go client library and OAuth2 package using the following commands:\n\n go get -u google.golang.org/api/youtube/v3\n go get -u golang.org/x/oauth2/...\n\nStep 3: Set up the sample\n-------------------------\n\nCreate a file named `quickstart.go` in your working directory and copy\nin the following code:\n\n\n```go\n// Sample Go code for user authorization\n\npackage main\n\nimport (\n \"encoding/json\"\n \"fmt\"\n \"log\"\n \"io/ioutil\"\n \"net/http\"\n \"net/url\"\n \"os\"\n \"os/user\"\n \"path/filepath\"\n\n \"golang.org/x/net/context\"\n \"golang.org/x/oauth2\"\n \"golang.org/x/oauth2/google\"\n \"google.golang.org/api/youtube/v3\"\n)\n\nconst missingClientSecretsMessage = `\nPlease configure OAuth 2.0\n`\n\n// getClient uses a Context and Config to retrieve a Token\n// then generate a Client. It returns the generated Client.\nfunc getClient(ctx context.Context, config *oauth2.Config) *http.Client {\n cacheFile, err := tokenCacheFile()\n if err != nil {\n log.Fatalf(\"Unable to get path to cached credential file. %v\", err)\n }\n tok, err := tokenFromFile(cacheFile)\n if err != nil {\n tok = getTokenFromWeb(config)\n saveToken(cacheFile, tok)\n }\n return config.Client(ctx, tok)\n}\n\n// getTokenFromWeb uses Config to request a Token.\n// It returns the retrieved Token.\nfunc getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n authURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n fmt.Printf(\"Go to the following link in your browser then type the \"+\n \"authorization code: \\n%v\\n\", authURL)\n\n var code string\n if _, err := fmt.Scan(&code); err != nil {\n log.Fatalf(\"Unable to read authorization code %v\", err)\n }\n\n tok, err := config.Exchange(oauth2.NoContext, code)\n if err != nil {\n log.Fatalf(\"Unable to retrieve token from web %v\", err)\n }\n return tok\n}\n\n// tokenCacheFile generates credential file path/filename.\n// It returns the generated credential path/filename.\nfunc tokenCacheFile() (string, error) {\n usr, err := user.Current()\n if err != nil {\n return \"\", err\n }\n tokenCacheDir := filepath.Join(usr.HomeDir, \".credentials\")\n os.MkdirAll(tokenCacheDir, 0700)\n return filepath.Join(tokenCacheDir,\n url.QueryEscape(\"youtube-go-quickstart.json\")), err\n}\n\n// tokenFromFile retrieves a Token from a given file path.\n// It returns the retrieved Token and any read error encountered.\nfunc tokenFromFile(file string) (*oauth2.Token, error) {\n f, err := os.Open(file)\n if err != nil {\n return nil, err\n }\n t := &oauth2.Token{}\n err = json.NewDecoder(f).Decode(t)\n defer f.Close()\n return t, err\n}\n\n// saveToken uses a file path to create a file and store the\n// token in it.\nfunc saveToken(file string, token *oauth2.Token) {\n fmt.Printf(\"Saving credential file to: %s\\n\", file)\n f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n if err != nil {\n log.Fatalf(\"Unable to cache oauth token: %v\", err)\n }\n defer f.Close()\n json.NewEncoder(f).Encode(token)\n}\n\nfunc handleError(err error, message string) {\n if message == \"\" {\n message = \"Error making API call\"\n }\n if err != nil {\n log.Fatalf(message + \": %v\", err.Error())\n }\n}\n\nfunc channelsListByUsername(service *youtube.Service, part string, forUsername string) {\n call := service.Channels.List(part)\n call = call.ForUsername(forUsername)\n response, err := call.Do()\n handleError(err, \"\")\n fmt.Println(fmt.Sprintf(\"This channel's ID is %s. Its title is '%s', \" +\n \"and it has %d views.\",\n response.Items[0].Id,\n response.Items[0].Snippet.Title,\n response.Items[0].Statistics.ViewCount))\n}\n\n\nfunc main() {\n ctx := context.Background()\n\n b, err := ioutil.ReadFile(\"client_secret.json\")\n if err != nil {\n log.Fatalf(\"Unable to read client secret file: %v\", err)\n }\n\n // If modifying these scopes, delete your previously saved credentials\n // at ~/.credentials/youtube-go-quickstart.json\n config, err := google.ConfigFromJSON(b, youtube.YoutubeReadonlyScope)\n if err != nil {\n log.Fatalf(\"Unable to parse client secret file to config: %v\", err)\n }\n client := getClient(ctx, config)\n service, err := youtube.New(client)\n\n handleError(err, \"Error creating YouTube client\")\n\n channelsListByUsername(service, \"snippet,contentDetails,statistics\", \"GoogleDevelopers\")\n}\nhttps://github.com/youtube/api-samples/blob/07263305b59a7c3275bc7e925f9ce6cabf774022/go/quickstart.go\n```\n\n\u003cbr /\u003e\n\nStep 4: Run the sample\n----------------------\n\nBuild and run the sample using the following command from your working\ndirectory: \n\n go run quickstart.go\n\nThe first time you run the sample, it will prompt you to authorize access:\n\n1. Browse to the provided URL in your web browser.\n\n If you are not already logged into your Google account, you will be\n prompted to log in. If you are logged into multiple Google accounts, you\n will be asked to select one account to use for the authorization.\n2. Click the **Accept** button.\n3. Copy the code you're given, paste it into the command-line prompt, and press **Enter**.\n\nIt worked! **Great!** Check out the further reading section below to learn more.\nI got an error **Bummer.** Thanks for letting us know and we'll work to fix this quickstart.\n\nNotes\n-----\n\n- Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.\n- The authorization flow in this example is designed for a command-line application. For information on how to perform authorization in a web application, see [Using OAuth 2.0 for Web Server Applications](/youtube/v3/guides/auth/server-side-web-apps).\n\nFurther reading\n---------------\n\n- [Google Developers Console help documentation](/console/help/new)\n- [Google APIs Client for Go](https://github.com/google/google-api-go-client)\n- [YouTube Data API reference documentation](/youtube/v3/docs)"]]