21

I am working with youtube api. when I hit this url "https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=2015-01-01&end-date=2016-01-31&metrics=likes%2Cdislikes&key={API Key}"

it gives 401

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

but I hited in the explorer "https://developers.google.com/apis-explorer/?" it working fine.
How do I make the first request work?

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
Kishore
  • 5,761
  • 5
  • 28
  • 53

2 Answers2

27

In your request you are sending key={your key} for an access token you should be sending access_token={your oauth2 access token}

Note: Key is used for public requests. access token is for authenticated requests.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • Is there a way to just use my key without an Oauth token? I know it's not secure, but this is just a proof of concept I'm trying to draw up real quick. And will probably replace with Oauth later – Max Coplan Apr 23 '20 at 14:00
6

If someone else using JWT authentication on a Google API stumbles upon this question (eg. when using Service Accounts) then make sure to include auth: <your jwtClient> in your API call, like:

First, get the token:

// Configure JWT auth client
var privatekey = require("./<secret>.json")
var jwtClient = new google.auth.JWT(
  privatekey.client_email,
  null,
  privatekey.private_key,
  ['https://www.googleapis.com/auth/drive']
);

// Authenticate request
jwtClient.authorize(function (err, tokens) {
  if (err) {
    return;
  } else {
    console.log("Google autorization complete");
  }
});

Then, call the API (but don't forget the auth:jwtClient part)

drive.files.create({
    auth: jwtClient,
    resource: {<fileMetadata>},
    fields: 'id'
  }, function (err, file) {
    if (err) {
      // Handle error
    } else {
      // Success is much harder to handle
    }
});
David Salamon
  • 2,361
  • 25
  • 30