Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Completa i passaggi descritti nel resto di questa pagina e in circa cinque minuti
avrai una semplice applicazione a riga di comando Go che effettua richieste all'API di dati di YouTube.
Il codice di esempio utilizzato in questa guida recupera la risorsa channel
per il canale YouTube GoogleDevelopers e stampa alcune informazioni di base
da questa risorsa.
Prerequisiti
Per eseguire questa guida rapida, devi disporre di:
Utilizza
questa procedura guidata
per creare o selezionare un progetto nella Google Developers Console e
attivare automaticamente l'API. Fai clic su Continua, quindi su
Vai alle credenziali.
Nella pagina Crea credenziali, fai clic sul pulsante
Annulla.
Nella parte superiore della pagina, seleziona la scheda Schermata di consenso OAuth.
Seleziona un indirizzo email, inserisci un nome prodotto se non
è già impostato e fai clic sul pulsante Salva.
Seleziona la scheda Credenziali, fai clic sul pulsante Crea credenziali
e seleziona ID client OAuth.
Seleziona il tipo di applicazione Altro, inserisci il nome
"Guida rapida all'API YouTube Data" e fai clic sul pulsante Crea.
Fai clic su Ok per chiudere la finestra di dialogo risultante.
Fai clic sul pulsante file_download
(Scarica JSON) a destra dell'ID client.
Sposta il file scaricato nella directory di lavoro e rinominalo
client_secret.json.
Passaggio 2: prepara lo spazio di lavoro
Imposta la variabile di ambiente GOPATH sulla directory di lavoro.
Scarica la libreria client Go dell'API YouTube Data e il pacchetto OAuth2
utilizzando i seguenti comandi:
go get -u google.golang.org/api/youtube/v3go get -u golang.org/x/oauth2/...
Passaggio 3: configura il campione
Crea un file denominato quickstart.go nella directory di lavoro e copia il seguente codice:
// 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")}
Crea ed esegui l'esempio utilizzando il seguente comando dalla tua directory di lavoro:
go run quickstart.go
La prima volta che esegui l'esempio, ti verrà chiesto di autorizzare l'accesso:
Vai all'URL fornito nel browser web.
Se non hai ancora eseguito l'accesso al tuo Account Google, ti verrà chiesto di farlo. Se hai eseguito l'accesso a più Account Google, ti verrà chiesto di selezionarne uno da utilizzare per l'autorizzazione.
Fai clic sul pulsante Accetta.
Copia il codice che ti viene fornito, incollalo nel prompt della riga di comando e premi
Invio.
Note
Le informazioni di autorizzazione vengono archiviate nel file system, quindi le esecuzioni successive non richiederanno l'autorizzazione.
Il flusso di autorizzazione in questo esempio è progettato per un'applicazione
a riga di comando. Per informazioni su come eseguire l'autorizzazione in un'applicazione web, consulta l'articolo sull'utilizzo di OAuth 2.0 per applicazioni server web.
[null,null,["Ultimo aggiornamento 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)"]]