Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Suivez les étapes décrites sur cette page. En cinq minutes environ, vous disposerez d'une application de ligne de commande Go simple qui envoie des requêtes à l'API YouTube Data.
L'exemple de code utilisé dans ce guide récupère la ressource channel pour la chaîne YouTube GoogleDevelopers et affiche des informations de base à partir de cette ressource.
Prérequis
Pour exécuter ce guide de démarrage rapide, vous avez besoin des éléments suivants :
Utilisez cet assistant pour créer ou sélectionner un projet dans la Google Developers Console et activer automatiquement l'API. Cliquez sur Continuer, puis sur Accéder à Identifiants.
Sur la page Créer des identifiants, cliquez sur le bouton Annuler.
En haut de la page, sélectionnez l'onglet OAuth consent screen (Écran d'autorisation OAuth).
Sélectionnez une adresse e-mail, saisissez un nom de produit s'il n'est pas déjà défini, puis cliquez sur le bouton Enregistrer.
Sélectionnez l'onglet Identifiants, cliquez sur le bouton Créer des identifiants, puis sélectionnez ID client OAuth.
Sélectionnez le type d'application Autre, saisissez le nom "Démarrage rapide de l'API YouTube Data", puis cliquez sur le bouton Créer.
Cliquez sur OK pour fermer la boîte de dialogue qui s'affiche.
Cliquez sur le bouton file_download (Télécharger JSON) à droite de l'ID client.
Déplacez le fichier téléchargé vers votre répertoire de travail et renommez-le client_secret.json.
Étape 2 : Préparez l'espace de travail
Définissez la variable d'environnement GOPATH sur votre répertoire de travail.
Obtenez la bibliothèque cliente Go de l'API YouTube Data et le package OAuth2 à l'aide des commandes suivantes :
go get -u google.golang.org/api/youtube/v3go get -u golang.org/x/oauth2/...
Étape 3 : Configurer l'exemple
Créez un fichier nommé quickstart.go dans votre répertoire de travail et copiez-y le code suivant :
// 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")}
Créez et exécutez l'exemple à l'aide de la commande suivante à partir de votre répertoire de travail :
go run quickstart.go
La première fois que vous exécutez l'exemple, vous êtes invité à autoriser l'accès :
Accédez à l'URL fournie dans votre navigateur Web.
Si vous n'êtes pas encore connecté à votre compte Google, vous serez invité à le faire. Si vous êtes connecté à plusieurs comptes Google, vous serez invité à en sélectionner un pour l'autorisation.
Cliquez sur le bouton Accepter.
Copiez le code qui vous est fourni, collez-le dans l'invite de ligne de commande, puis appuyez sur Entrée.
Remarques
Les informations d'autorisation sont stockées dans le système de fichiers. Les exécutions ultérieures ne vous demanderont donc pas d'autorisation.
Dans cet exemple, le flux d'autorisation est conçu pour une application en ligne de commande. Pour savoir comment effectuer l'autorisation dans une application Web, consultez Utiliser OAuth 2.0 pour les applications de serveur Web.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/21 (UTC).
[null,null,["Dernière mise à jour le 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)"]]