Yt Ruby Client

repository·master·Indexed 20 days ago

https://github.com/claudiob/yt

A Ruby client for interacting with the YouTube Data API (v3) and YouTube Analytics API. It provides high-level abstractions for managing YouTube accounts, channels, videos, playlists, and Content Owner (CMS) resources. Features include OAuth authentication flow, resource collection pagination, instrumentation via ActiveSupport::Notifications, and a CLI tool for video information.

Tokens
9.4K
Snippets
38
Records
52
Agent score
72%

What's inside Yt

  1. Monitor YouTube API requests with Instrumentation

    master

    Yt uses ActiveSupport::Notifications to allow monitoring of HTTP requests made to YouTube. You can subscribe to the request.yt event to track quota usage, request duration, or audit trails.

    Payload available in the event:

    • request_uri: The full URI of the request.
    • method: The HTTP method (e.g., :get).
    • response: The Net::HTTP response object.
    • duration: The time taken for the request.
    ActiveSupport::Notifications.subscribe 'request.yt' do |*args|
      event = ActiveSupport::Notifications::Event.new(*args)
    
      puts event.payload[:request_uri]
      puts event.payload[:method]
      puts event.duration
    end
  2. Install the Yt gem

    master

    To install Yt on your system, run the following command:

    gem install yt

    To use it in a Ruby project with a Gemfile, add:

    gem 'yt', '~> 0.34.0'

    It is recommended to use the pessimistic operator (~>) to ensure compatibility with Semantic Versioning.

  3. Authenticate a YouTube account via OAuth flow

    master

    To allow users to authorize your app, generate an authentication URL and then exchange the resulting code for an account instance.

    1. Generate the URL:
    # Define scopes like 'youtube', 'youtube.readonly', or 'userinfo.email'
    auth_url = Yt::Account.new(scopes: scopes, redirect_uri: redirect_uri).authentication_url
    1. Exchange the code: After the user is redirected to your redirect_uri with a code parameter, initialize the account:
    account = Yt::Account.new(authorization_code: 'CODE_FROM_PARAMS', redirect_uri: redirect_uri)
    # Step 1: Generate URL
    Yt::Account.new(scopes: scopes, redirect_uri: redirect_uri).authentication_url
    
    # Step 2: Initialize with code
    account = Yt::Account.new authorization_code: '4/Ja60jJ7_Kw0', redirect_uri: redirect_uri
  4. Establish a client with OAuth 2.0

    master

    Unlike youtube_it, Yt only supports OAuth 2.0 authentication. You can authenticate as a YouTube Account or as a ContentOwner (CMS account).

    To use OAuth 2.0, first configure the global Yt settings with your credentials, then initialize an Account or ContentOwner with your access and refresh tokens.

    Yt.configure do |config|
      config.client_id = 'client_id'
      config.client_secret = 'client_secret'
    end
    
    account = Yt::Account.new access_token: 'access_token', refresh_token: 'refresh_token'
  5. Use the Yt module to interact with YouTube resources

    master

    The Yt module serves as the primary entrypoint for an object-oriented Ruby client designed to interact with YouTube. It provides access to:

    • YouTube Data API V3 resources: Including channels, videos, playlists, and comment threads.
    • YouTube Analytics API V2 resources: Including metrics and estimated revenue.
    • Non-API objects: Such as annotations.

    To use the library, require yt in your Ruby application. The library is structured around model objects representing specific YouTube entities.

  6. Iterate through resource collections using pagination

    master

    When calling list methods on resource collections (like Yt::Video.list or Yt::Channel.list), the library provides an Enumerator that automatically handles YouTube API pagination. You can use standard Ruby Enumerable methods such as each, map, select, take, or first to traverse the results.

    Important Note on total_results: The total_results method returns the value from YouTube's pageInfo.totalResults field. According to YouTube documentation, this number is a size estimation and may not match the actual number of items returned (e.g., it might include inactive channels that are filtered out). To get the exact count, you must iterate through all pages, which will trigger multiple API requests.

    # Example: Taking only the first 10 videos from a search or list
    videos = Yt::Video.list(search_query: 'ruby programming')
    first_ten = videos.take(10)
    
    # Example: Iterating through all items (will trigger multiple requests)
    videos.each do |video|
      puts video.snippet.title
    end
  7. Configure Yt for read-only public data access

    master

    If your application only needs to fetch public data (read-only) and does not require user interaction, you only need a Public API access (Server Key) from the Google Developers Console.

    Configure it using the Yt.configure block:

    Yt.configure do |config|
      config.api_key = 'YOUR_API_KEY'
    end

    Note: This mode cannot perform destructive operations like liking videos, subscribing to channels, or deleting playlists.

    Yt.configure do |config|
      config.api_key = 'AIzaSyAO8dXpvZcaP2XSDFBD91H8yQ'
    end
  8. Configure Yt for web apps with user authentication

    master

    For web applications that manage YouTube accounts, you must provide client_id and client_secret obtained from the Google Developers Console (OAuth section).

    Yt.configure do |config|
      config.client_id = 'YOUR_CLIENT_ID'
      config.client_secret = 'YOUR_CLIENT_SECRET'
    end

    Alternatively, you can use environment variables:

    export YT_CLIENT_ID="YOUR_CLIENT_ID"
    export YT_CLIENT_SECRET="YOUR_CLIENT_SECRET"

    If both are provided, Yt.configure takes precedence.

    Yt.configure do |config|
      config.client_id = '1234567890.apps.googleusercontent.com'
      config.client_secret = '1234567890'
    end
  9. Initialize a resource using a YouTube URL

    master

    The Yt::Models::Resource base class allows initializing resource objects using a YouTube URL. The library uses internal regex patterns to extract the resource ID and type from the URL.

    Supported URL patterns include:

    • Videos: youtube.com/watch?v=..., youtu.be/..., youtube.com/embed/..., youtube.com/v/..., and youtube.com/shorts/....
    • Playlists: youtube.com/playlist?list=....
    • Channels: youtube.com/channel/..., youtube.com/user/..., youtube.com/c/..., and handle-based URLs like youtube.com/@handle.

    Note for Channels: If a channel is initialized via a handle (e.g., @handle) or username, the library may attempt to fetch the actual channel ID using the configured Yt.configuration.api_key.

    # Example of initializing a resource via URL
    video = Yt::Video.new(url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ')
    puts video.id # Extracts the ID from the URL
  10. Enable verbose error details for troubleshooting

    master

    By default, RequestError provides a minimal message. To see full error details, including the response body and the curl command required to manually retry the request, you must enable debug logging in the Yt configuration.

    Configure the log_level to :debug using the Yt.configure block.

    Yt.configure do |config|
      config.log_level = :debug
    end
  11. Manage Playlists and Playlist Items

    master

    Playlists can be managed via the Yt::Account or Yt::Playlist classes.

    • Create Playlist: account.create_playlist(title: '...', description: '...').
    • List Playlists: account.playlists returns the playlists for the account.
    • Add Video to Playlist: Use playlist.add_video(video_id, position: position).
    • Remove Video from Playlist: Use playlist_item.delete on a Yt::PlaylistItem instance.
    • Update Position: Use playlist_item.update(position: new_position) on a Yt::PlaylistItem instance.
    account = Yt::Account.new access_token: 'access_token'
    
    # Create
    playlist = account.create_playlist title: 'new playlist', description: 'description'
    
    # Add video
    playlist.add_video 'video_id', position: 1
    
    # Remove video
    item = Yt::PlaylistItem.new id: 'playlist_entry_id', auth: account
    item.delete