Skip to content

Latest commit

 

History

History
472 lines (351 loc) · 13 KB

File metadata and controls

472 lines (351 loc) · 13 KB

yt-api

yt-api CLI Demo

Manage your YouTube account from the command line. A complete CLI for the YouTube Data API v3, perfect for automation, scripting, and power users.

Features

  • Complete API coverage - Full support for YouTube Data API v3 (videos, playlists, channels, comments, and more)
  • Multiple output formats - JSON, YAML, CSV, or human-readable tables
  • Flexible authentication - OAuth 2.0 for personal use or service accounts for automation
  • Powerful uploads - Upload videos from files, URLs, or stdin with progress tracking
  • Automation-ready - Structured output and error handling perfect for scripts and tools

Installation

Pre-built binaries (recommended)

macOS:

# Apple Silicon (M1/M2/M3)
curl -L -o yt-api https://github.com/nerveband/youtube-api-cli/releases/latest/download/yt-api-darwin-arm64
chmod +x yt-api
sudo mv yt-api /usr/local/bin/

# Intel
curl -L -o yt-api https://github.com/nerveband/youtube-api-cli/releases/latest/download/yt-api-darwin-amd64
chmod +x yt-api
sudo mv yt-api /usr/local/bin/

Linux:

# AMD64
curl -L -o yt-api https://github.com/nerveband/youtube-api-cli/releases/latest/download/yt-api-linux-amd64
chmod +x yt-api
sudo mv yt-api /usr/local/bin/

# ARM64
curl -L -o yt-api https://github.com/nerveband/youtube-api-cli/releases/latest/download/yt-api-linux-arm64
chmod +x yt-api
sudo mv yt-api /usr/local/bin/

Windows: Download yt-api-windows-amd64.exe and add to your PATH.

From source

# Using go install
go install github.com/nerveband/youtube-api-cli/cmd/yt-api@latest

# Or build locally
git clone https://github.com/nerveband/youtube-api-cli.git
cd youtube-api-cli
go build -o yt-api ./cmd/yt-api

Quick Start

1. Set Up Google Cloud Credentials

  1. Go to Google Cloud Console
  2. Create a new project (or select existing)
  3. Enable the YouTube Data API v3
  4. Create OAuth 2.0 credentials (Desktop application type)
  5. Download the client configuration

2. Configure yt-api

# Create config directory
mkdir -p ~/.yt-api

# Create config file with your OAuth credentials
cat > ~/.yt-api/config.yaml << EOF
default_auth: oauth
default_output: json
oauth:
  client_id: "YOUR_CLIENT_ID"
  client_secret: "YOUR_CLIENT_SECRET"
EOF

3. Authenticate

# OAuth login (opens browser)
yt-api auth login

# Check auth status
yt-api auth status

4. Start Using

# List your videos
yt-api list videos --mine

# Search for videos
yt-api search --query "golang tutorial" --max-results 10

# Upload a video
yt-api upload video ./video.mp4 --title "My Video" --description "Description here"

Usage

Command Structure

yt-api <action> <resource> [flags]

Actions: list, insert, update, delete, upload, download, search, auth, rate, set, unset, moderate, report

Resources: videos, channels, playlists, playlist-items, comments, comment-threads, captions, subscriptions, and more.

Global Flags

Flag Short Description
--output -o Output format: json (default), yaml, csv, table
--quiet -q Suppress stderr messages
--config Path to config file
--auth-type Auth method: oauth (default), service-account

Examples

List Operations

# List videos from a channel
yt-api list videos --channel-id UC_x5XG1OV2P6uZZ5FSM9Ttw

# List your subscriptions
yt-api list subscriptions --mine

# List playlist items
yt-api list playlist-items --playlist-id PLxxxxxxx

# List with pagination
yt-api list videos --channel-id UCxxx --max-results 50 --page-token "TOKEN"

# Fetch all pages
yt-api list videos --channel-id UCxxx --all-pages

Search

# Basic search
yt-api search --query "cooking recipes"

# Search with filters
yt-api search --query "music" --type video --duration medium --order viewCount

Upload Operations

# Upload video from file
yt-api upload video ./my-video.mp4 \
  --title "My Awesome Video" \
  --description "Check out this video!" \
  --tags "tag1,tag2,tag3" \
  --privacy public

# Upload from stdin
cat video.mp4 | yt-api upload video - --title "Piped Video"

# Upload from URL
yt-api upload video https://example.com/video.mp4 --title "From URL"

# Upload thumbnail
yt-api upload thumbnail ./thumb.jpg --video-id VIDEO_ID

# Upload caption
yt-api upload caption ./captions.srt --video-id VIDEO_ID --language en

Playlist Management

# Create playlist
yt-api insert playlist --title "My Playlist" --privacy private

# Add video to playlist
yt-api insert playlist-item --playlist-id PLxxx --video-id VIDxxx

# Update playlist
yt-api update playlist --id PLxxx --title "New Title"

# Delete playlist
yt-api delete playlist --id PLxxx

Channel Operations

# Get channel info
yt-api list channels --id UCxxx --part snippet,statistics

# Update channel (requires ownership)
yt-api update channel --id UCxxx --description "New description"

Output Formats

# JSON (default) - best for LLMs and scripts
yt-api list videos --mine
{"items": [...], "pageInfo": {"totalResults": 42}}

# Table - human readable
yt-api list videos --mine -o table
ID           TITLE                 VIEWS    PUBLISHED
abc123       My First Video        1000     2024-01-15
def456       Another Video         500      2024-01-20

# YAML
yt-api list videos --mine -o yaml

# CSV
yt-api list videos --mine -o csv > videos.csv

Authentication Methods

OAuth 2.0 (Default)

Best for interactive use and accessing your own YouTube account.

yt-api auth login
# Opens browser for Google login
# Tokens stored in ~/.yt-api/tokens.json

Service Account

Best for server-side automation with dedicated YouTube channels.

# Via flag
yt-api --auth-type service-account --credentials ./key.json list videos

# Via environment
export YT_API_AUTH_TYPE=service-account
export YT_API_CREDENTIALS=/path/to/key.json
yt-api list videos

Environment Variables

Variable Description
YT_API_AUTH_TYPE Auth method: oauth or service-account
YT_API_OUTPUT Default output format
YT_API_CLIENT_ID OAuth client ID
YT_API_CLIENT_SECRET OAuth client secret
YT_API_CREDENTIALS Path to service account JSON

Configuration

Config File Location

Configuration is stored in ~/.yt-api/config.yaml. Run yt-api info to see all file paths.

Config File Format

default_auth: oauth
default_output: json
oauth:
  client_id: "YOUR_CLIENT_ID"
  client_secret: "YOUR_CLIENT_SECRET"
service_account:
  credentials_file: "/path/to/service-account.json"

File Locations

File Path Purpose
Config ~/.yt-api/config.yaml Main configuration
OAuth Token ~/.yt-api/tokens.json OAuth tokens (0600 permissions)
Update Cache ~/.yt-api/cache/update_check.json Version check cache

Security Notes

  • OAuth tokens are stored in plain text with restricted permissions (0600)
  • Never commit ~/.yt-api/ to version control
  • Service account keys should have minimal required permissions

Permissions

YouTube API Scopes

yt-api requests the https://www.googleapis.com/auth/youtube scope for full YouTube access.

Operation Requirements

Operation Auth Required Notes
list videos --id No Public videos
list videos --mine Yes Your videos
search No Public search
insert/update/delete Yes Must own resource
upload Yes Uploads to your channel

Testing Permissions

yt-api info --test-permissions

Error Handling

Errors output structured JSON to stdout (for parsing) and human-readable details to stderr:

stdout:

{"error": {"code": "quotaExceeded", "message": "...", "status": 403}}

stderr:

Error: YouTube API quota exceeded.
  Used: 10,000 / 10,000 units today
  This request costs: 1,600 units (video upload)
  Resets: 2024-01-24 00:00:00 PST
  Increase quota: https://console.cloud.google.com/apis/api/youtube.googleapis.com/quotas

Exit Codes:

  • 0 - Success
  • 1 - General error
  • 2 - Authentication error
  • 3 - API error (quota, permissions)
  • 4 - Input error (bad flags, missing params)

For LLMs and Automated Agents

This CLI is designed for easy integration with LLMs and automation tools:

  1. JSON output by default - No parsing human-readable text
  2. Structured errors - Errors are JSON objects with codes and details
  3. Quiet mode - --quiet suppresses all non-essential output
  4. Dry run - --dry-run validates without executing
  5. Stdin support - Pipe data directly from other tools
  6. Predictable pagination - Use --page-token or --all-pages

Quick Diagnostic Commands

yt-api info                     # Full system state
yt-api info --test-connectivity # Verify API access
yt-api info --test-permissions  # Check credential capabilities
yt-api auth status              # Authentication details
yt-api version                  # Version info

Keeping Updated

yt-api upgrade --check          # Check for updates
yt-api upgrade                  # Install latest version

When to upgrade:

  • Before starting new automation tasks
  • After encountering unexpected errors
  • When documentation mentions unavailable features
  • When you see "Update available" notification

Troubleshooting

Problem Solution
Auth errors yt-api auth login
Quota errors Wait until midnight PT
Permission errors yt-api info --test-permissions
Unknown errors yt-api upgrade then retry

Best Practices

  1. Use --quiet when parsing JSON output
  2. Use --dry-run before write operations
  3. Run yt-api info first when debugging
  4. Check exit codes (0=success, 1-4=various errors)

Example LLM workflow

# Get video list as JSON
videos=$(yt-api list videos --mine -q)

# Parse and process with jq or other tools
echo "$videos" | jq '.items[].id'

API Coverage

Resource list insert update delete Other
Videos ✓ (upload) rate, reportAbuse
Channels - - -
Playlists -
PlaylistItems -
PlaylistImages -
Comments setModerationStatus
CommentThreads - - -
Captions ✓ (upload) download
Subscriptions - -
ChannelSections -
Thumbnails - ✓ (set) - - -
Watermarks - - - - set, unset
Search - - - -
i18nLanguages - - - -
i18nRegions - - - -
VideoCategories - - - -
Members - - - -
MembershipsLevels - - - -

Project Structure

youtube-api-cli/
├── cmd/
│   └── yt-api/          # Main CLI entry point
├── internal/
│   ├── apierror/        # Error handling and formatting
│   ├── auth/            # OAuth and service account authentication
│   ├── client/          # YouTube API client wrapper
│   ├── commands/        # Command implementations (list, insert, update, etc.)
│   ├── config/          # Configuration management
│   ├── output/          # Output formatters (JSON, YAML, CSV, table)
│   ├── update/          # Auto-update checking with caching
│   └── upload/          # File upload with progress tracking
├── docs/
│   ├── SETUP_GUIDE.md           # Detailed setup and testing guide
│   ├── WRITE_OPERATIONS_GUIDE.md # Insert/update/delete operations guide
│   └── plans/                    # Design documents
└── Makefile             # Build and test commands

Key Components

  • Commands - Each YouTube API resource (videos, playlists, etc.) has its own command package
  • Authentication - Supports both OAuth 2.0 (interactive) and service accounts (automation)
  • Output Formatting - Pluggable formatters for different output formats
  • Error Handling - Structured errors with helpful messages and quota information
  • Upload System - Resumable uploads with progress tracking for videos and captions

Documentation

Contributing

Contributions welcome! Please read the design document first.

License

MIT