You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问YouTube品牌账号API?Node.js调用YT Analytics API遭Forbidden

解决YouTube品牌账号API访问及YT Analytics Forbidden错误问题

Hey there, let’s work through your two issues—getting access to the YouTube Brand Account API and fixing that frustrating "Forbidden" error when using the YT Analytics API with Node.js and the googleapis library. I’ve helped several developers sort out similar problems, so here’s a detailed breakdown:

1. 访问YouTube品牌账号API的核心步骤

Before diving into the error fix, let’s make sure you’ve covered the basics to access the Brand Account API:

  • Enable Required APIs First
    Head to your Google Cloud Console, find your project, and enable both the YouTube Data API v3 and YouTube Analytics API. Without these enabled, no requests will work, regardless of your auth setup.

  • Configure Service Account with Domain-Wide Delegation
    You mentioned creating a service account with a Gmail admin account, but you likely missed this critical step:

    1. In the Google Cloud Console, go to your service account’s details page, copy its Client ID.
    2. Log into your Google Workspace Admin Console (since you’re using an admin account), navigate to Security > API Controls > Domain-wide Delegation.
    3. Add a new entry using the service account’s Client ID, and paste these API scopes (adjust based on your needs):
      • https://www.googleapis.com/auth/yt-analytics.readonly (for analytics data)
      • https://www.googleapis.com/auth/youtube.readonly (for basic channel data)
      • https://www.googleapis.com/auth/youtube (if you need write access)
  • Grant Service Account Access to Your Brand Account
    Service accounts can’t automatically access Brand Accounts—you need to add them as a user to the account:

    1. Go to YouTube Studio and log into the Brand Account you want to access.
    2. Click on Settings > Permissions.
    3. Click Invite and enter the service account’s email address (found in your service account JSON key file). Assign a role like Viewer (for analytics) or Owner (if you need full access).

2. Fixing the "Forbidden" Error in Node.js Requests

The Forbidden error almost always boils down to missing permissions or incorrect request configuration. Here’s how to fix it, plus a working code example:

Common Causes & Fixes

  • You’re not specifying the Brand Account in your request
    Service accounts don’t have their own YouTube channels, so you need to explicitly tell the API which Brand Account/channel to access. Use either the onBehalfOfContentOwner (for content owner accounts) or specify the channel ID in the ids parameter of your analytics request.

  • Incorrect or Missing API Scopes
    Double-check that the scopes you added in Domain-Wide Delegation match the ones in your Node.js code. Mismatched scopes will trigger Forbidden errors.

  • Service Account isn’t added to the Brand Account’s permissions
    Even if you set up domain-wide delegation, if the service account isn’t listed in the Brand Account’s permissions, it can’t access the data. Double-check the YouTube Studio permissions page.

Working Node.js Code Example

Here’s a cleaned-up snippet that includes all the necessary setup:

const { google } = require('googleapis');
// Replace with the path to your service account key file
const serviceAccountKey = require('./your-service-account-key.json');

// Initialize JWT auth with the required scopes
const auth = new google.auth.JWT(
  serviceAccountKey.client_email,
  null,
  serviceAccountKey.private_key,
  [
    'https://www.googleapis.com/auth/yt-analytics.readonly',
    'https://www.googleapis.com/auth/youtube.readonly'
  ],
  null // Leave this null for Brand Account access (no impersonated user needed)
);

// Initialize the YouTube Analytics API client
const youtubeAnalytics = google.youtubeAnalytics('v2');

async function fetchBrandAccountAnalytics() {
  try {
    // Authorize the client first
    await auth.authorize();

    // Replace with your Brand Account's channel ID
    const brandChannelId = 'YOUR_BRAND_ACCOUNT_CHANNEL_ID';

    const response = await youtubeAnalytics.reports.query({
      auth: auth,
      // Use 'channel==CHANNEL_ID' for a specific Brand Account channel
      ids: `channel==${brandChannelId}`,
      startDate: '2024-01-01',
      endDate: '2024-01-31',
      metrics: 'views,estimatedMinutesWatched',
      dimensions: 'day'
    });

    console.log('Analytics Data:', response.data);
  } catch (error) {
    console.error('Error fetching analytics:', error.response?.data || error.message);
  }
}

// Run the function
fetchBrandAccountAnalytics();

Quick Checks After Setting Up

  1. Verify that YOUR_BRAND_ACCOUNT_CHANNEL_ID is correct—you can find this in YouTube Studio under Settings > Channel > Advanced Settings.
  2. Ensure your service account key file is correctly referenced and hasn’t expired.
  3. Wait 5-10 minutes after making permission changes—Google’s systems can take a bit to propagate updates.

内容的提问来源于stack exchange,提问作者praveenK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:18:37