Search code examples
google-apiyoutube-data-apigoogle-api-nodejs-client

Using API key with node js google library


I am trying to consume google youtube data apis which has support for api key type of credentials.

https://developers.google.com/youtube/registering_an_application

I am trying to use google auth library for node js to communicate with the apis

https://github.com/googleapis/google-auth-library-nodejs

There is an example of this API with oAuth credentials and service account credentials.

I know that api key is supposed to be used by client side applications like browser based javascripts. So i see example with browser based google apis.

But is there any example where api keys can be used with google node js client library ?

Best Regards,

Saurav


Solution

  • You can use Google API NodeJS client using an API key on NodeJS. Just put the API key instead of the oauth client in the auth field :

    "use strict"
    
    const {google} = require('googleapis');
    
    const youtube = google.youtube({
      version: 'v3',
      auth: 'YOUR_API_KEY'
    });
    
    youtube.search.list({
        part: 'id,snippet',
        q: 'Node.js on Google Cloud',
    }).then(res => {
        console.log(res.data);
    })
    .catch(error => {
        console.error(error);
    });;
    

    There is this internal check in google-api-commons nodejs library which check if auth is a string and add the API key to the request in that case.