Get your dream built 10x faster

How to integrate YouTube with OpenClaw

We build custom applications 5x faster and cheaper 🚀

Book a Free Consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Stuck on an error? Book a 30-minute call with an engineer and get a direct fix + next steps. No pressure, no commitment.

How to integrate YouTube with OpenClaw

 

Direct answer

 

Integrate YouTube with OpenClaw by building a small external web service that performs the OAuth 2.0 authorization code flow against Google, stores refresh/access tokens in a secure store, exposes a webhook endpoint for YouTube push notifications (PubSubHubbub/WebSub), and registers a skill in ClawHub that references those credentials and webhook URL. The OpenClaw skill should call Google’s YouTube Data API with the stored Bearer tokens (or use an API key for public-only reads), and long-lived concerns (token storage, webhook handling, scheduled refresh) must run outside the agent runtime. Debug with logs and API responses, verify OAuth scopes and webhook verification, and respect quotas and retry semantics.

 

What you need (high level)

 
  • Google Cloud project with OAuth 2.0 client ID/secret and YouTube Data API enabled.
  • An external HTTPS web service (callback/webhook) that OpenClaw skills can securely reference.
  • Secure storage for tokens (vault, secrets manager, or environment variables injected by ClawHub).
  • ClawHub configuration for the skill: OAuth client creds (or link to them), environment variables for tokens/keys, and the webhook URL.
  • Skill code that makes authenticated REST calls to YouTube Data API endpoints using Bearer tokens.

 

Key concepts explained simply

 
  • OAuth 2.0 Authorization Code flow: The user grants permissions in Google’s consent screen. Your web service receives a code on the redirect URI and exchanges it for tokens. The service saves refresh tokens so you can get new access tokens later (offline access).
  • YouTube Data API: Standard REST endpoints (GET/POST) authenticated with OAuth Bearer tokens or API key for public data. Calls look like HTTPS requests to https://www.googleapis.com/youtube/v3/...
  • Push notifications (WebSub / PubSubHubbub): YouTube can publish notifications (channel activity) to a webhook URL. Your webhook must implement the GET challenge response and accept POST notifications.
  • OpenClaw placement: The agent/runtime should call your external service or read tokens injected by ClawHub. Don’t rely on the agent to securely persist long-term state or run reliable webhooks—those should be external.

 

Step-by-step implementation

 
  • 1) Create Google credentials and enable APIs
    • Create a Google Cloud project, enable the YouTube Data API v3.
    • Create OAuth credentials (Web application) and set the redirect URI to your external service (e.g., https://your-service.example.com/oauth/callback).
    • Decide required OAuth scopes (examples: https://www.googleapis.com/auth/youtube.readonly, https://www.googleapis.com/auth/youtube.upload). Request the least privilege needed.
  • 2) Implement OAuth callback and token storage (external service)
    • Redirect users to Google’s auth URL (example):
// Example authorization URL (open in browser)
https://accounts.google.com/o/oauth2/v2/auth?client_id=YOUR_CLIENT_ID&redirect_uri=https://your-service.example.com/oauth/callback&response_type=code&scope=https://www.googleapis.com/auth/youtube.readonly%20https://www.googleapis.com/auth/youtube.upload&access_type=offline&prompt=consent
  • Exchange code for tokens (example curl):
// Exchange authorization code for tokens
curl -X POST https://oauth2.googleapis.com/token \
  -d client_id=YOUR_CLIENT_ID \
  -d client_secret=YOUR_CLIENT_SECRET \
  -d code=AUTH_CODE \
  -d redirect_uri=https://your-service.example.com/oauth/callback \
  -d grant_type=authorization_code
  • Save the returned access_token, refresh_token, expires\_in, and associated channel/user ID in a secure store (database + secrets manager or encrypted DB).
  • Implement token refresh: POST to https://oauth2.googleapis.com/token with grant_type=refresh_token when access tokens expire.
  • 3) Implement YouTube PubSubHubbub webhook
    • YouTube uses WebSub-style push notifications. Your webhook must handle:
      • GET verification (hub.challenge) — respond with the hub.challenge value as text.
      • POST notifications — requests with an XML feed indicating updated resources; parse the message and then fetch full resource details from the YouTube Data API if needed.
  • // Minimal Node/Express webhook handler (verification + notification)
    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    app.use(bodyParser.text({ type: '*/*' })); // <b>//</b> PubSubHubbub sends XML or text
    
    // <b>//</b> Verification (GET)
    app.get('/youtube/webhook', (req, res) => {
      const mode = req.query['hub.mode'];
      const challenge = req.query['hub.challenge'];
      const topic = req.query['hub.topic'];
      // <b>//</b> Validate topic and mode as needed
      if (challenge) {
        res.status(200).send(challenge);
      } else {
        res.sendStatus(400);
      }
    });
    
    // <b>//</b> Notification (POST)
    app.post('/youtube/webhook', (req, res) => {
      const raw = req.body; // <b>//</b> XML body with <feed><entry>...
      // <b>//</b> Acknowledge quickly
      res.sendStatus(204);
      // <b>//</b> Parse raw XML and act: fetch video details with your stored tokens
    });
    app.listen(3000);
    
    • To subscribe to a topic, you POST a subscription request to the hub URL (as described in Google’s docs). The hub will call your GET endpoint to confirm. You can also use Google Pub/Sub for push subscriptions if preferred.
  • 4) Make YouTube Data API calls from your skill/runtime
    • When the skill needs data, it should call your external service which will use stored tokens to call Google, or the skill can call Google directly if ClawHub injected a valid access\_token as an environment variable (short-lived tokens are fine for immediate calls).
    • Example call to list a channel’s uploads (replace Bearer TOKEN):
    // Get channel details (example)
    curl -H "Authorization: Bearer ACCESS_TOKEN" \
      "https://www.googleapis.com/youtube/v3/channels?part=contentDetails,snippet&mine=true"
    
    • If you receive only a notification with an upload ID, call the videos endpoint to get metadata:
    // Get video metadata
    curl -H "Authorization: Bearer ACCESS_TOKEN" \
      "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=VIDEO_ID"
    
  • 5) Configure the skill in ClawHub
    • Register the skill package in ClawHub and set environment variables or secret bindings for:
      • GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET (if the skill will initiate OAuth), or a pointer to your token store service.
      • CALLBACK_URL and WEBHOOK_URL if needed.
      • Any API keys for public-only operations.
    • Expose the external webhook endpoint in your public infra and enter that URL in any place where subscriptions are initiated (your service will ask the hub to subscribe to channel topics).
    • Keep tokens and secrets in the ClawHub secret store rather than in skill code or repo.
  • 6) Runtime design: what runs where
    • Agent/skill code (OpenClaw runtime):
      • Should be short-lived, responsible for: calling your external service, formatting request/response, and invoking YouTube API for immediate, synchronous actions with available tokens.
    • External web service:
      • Must handle long-lived things: OAuth redirect endpoint, refresh-token logic, webhook verification and delivery, retries, background jobs (e.g., re-subscribing to topics), and storing tokens.
  •  

    Security, quotas, and operational notes

     
    • Scopes: Request only what you need. Some YouTube scopes are sensitive and require review by Google if your app is public.
    • Refresh tokens: Store securely and rotate if you detect suspicious activity. Refresh access tokens before expiration to avoid failures.
    • Webhook validation: Implement GET challenge response and validate topic and hub.mode. Rate-limit and verify incoming requests to prevent abuse.
    • Quota and retries: YouTube API enforces quotas. Implement exponential backoff and monitor quota usage in Google Cloud Console.
    • Secrets: Use a vault or ClawHub secret binding; do not hard-code client secrets in skill code.

     

    Common failure modes and how to debug

     
    • Invalid OAuth scopes or missing consent: Check the authorization URL and the scopes requested; verify user consent screen in Google Cloud console.
    • Expired/invalid tokens: Inspect token exchange responses and implement refresh-token flow; check error fields from API responses (401, token_required, invalid_grant).
    • Webhook not verified: Ensure your GET handler echoes hub.challenge exactly and that the webhook URL is reachable over HTTPS.
    • 403 / quotaExceeded: Use Google Cloud Console to inspect quota and billing; throttle requests and add retries.
    • Wrong resource ID or permission denied: Confirm the OAuth token belongs to a user/channel that has the permission for the requested operation.
    • Skill not invoked from OpenClaw: Check ClawHub skill logs, the skill configuration, and that environment variables/secrets were injected correctly. Make test calls from the skill runtime that log the outgoing request and response.

     

    Short checklist before launch

     
    • Google project + YouTube Data API enabled
    • OAuth client configured with correct redirect URIs
    • External webhook reachable over HTTPS and implements GET/POST handling
    • Secure token store for refresh/access tokens
    • ClawHub skill configured with secret bindings and env vars
    • Logging and monitoring for token refreshes, webhook deliveries, and API errors
    • Backoff and retry logic for API rate limits

     

    Final architectural recommendation

     

    Run the OAuth and webhook handling as a small dedicated web service (or serverless endpoints) outside the OpenClaw agent. Use the agent/skill only to perform immediate API calls or orchestrate user-facing behavior. Store refresh tokens and do scheduled token refreshes outside the agent. This separation gives you reliability, observability, and secure secret management while keeping the skill code simple and focused.

    Book Your Free 30‑Minute Migration Call

    Speak one‑on‑one with a senior engineer about your no‑code app, migration goals, and budget. In just half an hour you’ll leave with clear, actionable next steps—no strings attached.

    Book a Free Consultation

    Troubleshooting YouTube and OpenClaw Integration

    1

    OpenClaw YouTube connector OAuth2 redirect_uri_mismatch error when authorizing?

    The error means the OAuth redirect_uri sent in your YouTube/Google authorization request does not exactly match the URI registered for your OAuth client. Fix by making the URI strings identical (scheme, host, path, trailing slash) and by using the same value in OpenClaw/ClawHub skill config and the Google Cloud Console.

     

    Practical steps

     

    Check the redirect_uri your skill uses, register that exact value in Google Cloud -> OAuth 2.0 Client IDs, and ensure the skill/runtime env var points to the same URL. Use HTTPS for production, localhost for local testing.

    • Compare exact strings including trailing slash
    • Use env vars in your skill so runtime and console match
    • Confirm PKCE/state if used
    // Build auth URL using env var so it matches registered URI
    const redirect = process.env.OAUTH_REDIRECT_URI; // <b>//</b> must match Google Console
    const url = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${process.env.CLIENT_ID}&redirect_uri=${encodeURIComponent(redirect)}&response_type=code&scope=youtube.readonly&access_type=offline`;
    

    2

    OpenClaw YouTube connector API quota exceeded errors when importing videos?

     

    Direct answer

     

    Quota exceeded means the YouTube Data API limits were hit. Fixes: reduce request volume, use incremental imports and batching, implement exponential backoff with jitter, cache responses, move heavy ingestion outside the OpenClaw agent runtime, and request a quota increase in Google Cloud Console.

     

    Practical steps

     
    • Incremental sync: store lastImportTime outside the agent (DB/env).
    • Batch & filter: request only needed fields/parts and use playlistItems.
    • Backoff & retry: exponential backoff with jitter and respect 403/429 responses.
    • Monitor: check quota usage in Google Cloud Console and logs.
    // Node.js example: simple backoff + incremental import
    const axios = require('axios');
    const API_KEY = process.env.YT_API_KEY;
    // lastImport stored externally; example value:
    let lastImport = process.env.LAST_IMPORT_TS || 0;
    async function fetchNewVideos(pageToken, attempt=0){
      try{
        const res = await axios.get('https://www.googleapis.com/youtube/v3/playlistItems',{
          params:{playlistId:'UPLOADS_PLAYLIST_ID', part:'snippet', maxResults:50, pageToken, key:API_KEY, publishedAfter:lastImport}
        });
        return res.data;
      }catch(e){
        if ((e.response && [429,403].includes(e.response.status)) && attempt<5){
          await new Promise(r=>setTimeout(r, Math.pow(2,attempt)*1000 + Math.random()*500));
          return fetchNewVideos(pageToken, attempt+1);
        }
        throw e;
      }
    }
    

    3

    OpenClaw YouTube connector webhook (PubSubHubbub) callbacks not delivered or verification failing?

    Most likely the PubSubHubbub (WebSub) verification fails because the OpenClaw skill’s callback URL is unreachable, misconfigured, or not returning the exact verification response (echo hub.challenge) with a 200 status. Check TLS, redirects, verify_token, and that ClawHub/skill configuration uses the same callback URL and token.

     

    Quick checklist

     

    Fix steps:

    • Expose a public HTTPS URL (ngrok for dev) and ensure no redirects.
    • Respond to GET verification: return 200 and body = hub.challenge as plain text.
    • Match verify_token exactly between subscription and skill config.
    • Log incoming requests and full headers; inspect gateway/firewall and TLS certs.
    • Handle POSTs separately and validate any signatures if provided.

    4

    OpenClaw YouTube connector resumable upload returns 308 or fails to finalize video/thumbnail upload?

    If your OpenClaw YouTube connector returns 308 Resume Incomplete or fails to finalize uploads, it usually means the resumable session wasn’t completed (wrong Content-Range/offset, lost session URL, or wrong OAuth scope). Fix by ensuring correct headers, persisting the session URL outside the agent runtime, and retrying from the reported offset until the final chunk is accepted.

     

    Troubleshoot and fix

     

    Key checks:

    • Content-Range: match bytes exactly; final chunk must cover 0–(total-1).
    • Session URL: store the upload URL externally (DB/kv) so agents can resume.
    • Auth & scopes: token needs youtube.upload (and proper refresh).
    • Retries: on 308 read Range header, resume from next byte; handle network timeouts.
    • Thumbnail: upload after video creation; ensure correct API call and content-type.
    Book a Free Consultation

    Still stuck?
    Copy this prompt into ChatGPT and get a clear, personalized explanation.

    This prompt helps an AI assistant understand your setup and guide you through the fix step by step, without assuming technical knowledge.

    AI AI Prompt


    Recognized by the best

    Trusted by 600+ businesses globally

    From startups to enterprises and everything in between, see for yourself our incredible impact.

    RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

    They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

    Arkady
    CPO, Praction
    Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

    He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

    Donald Muir
    Co-Founder, Arc
    RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

    They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

    Mat Westergreen-Thorne
    Co-CEO, Grantify
    RapidDev is an excellent developer for custom-code solutions.

    We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

    Emmanuel Brown
    Co-Founder, Church Real Estate Marketplace
    Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

    This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

    Samantha Fekete
    Production Manager, Media Production Company
    The pSEO strategy executed by RapidDev is clearly driving meaningful results.

    Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

    Appreciation as well to Matt Graham for championing the collaboration!

    Michael W. Hammond
    Principal Owner, OCD Tech

    We put the rapid in RapidDev

    Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â