Struct YouTubeTranscriptApi

Source
pub struct YouTubeTranscriptApi { /* private fields */ }
Expand description

§YouTubeTranscriptApi

The main interface for retrieving YouTube video transcripts and metadata.

This API provides methods to:

  • Fetch transcripts from YouTube videos in various languages
  • List all available transcript languages for a video
  • Retrieve detailed video metadata

The API supports advanced features like:

  • Custom HTTP clients and proxies for handling geo-restrictions
  • Cookie management for accessing restricted content
  • Preserving text formatting in transcripts

§Simple Usage Example

use yt_transcript_rs::api::YouTubeTranscriptApi;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a new API instance with default settings
    let api = YouTubeTranscriptApi::new(None, None, None)?;
     
    // Fetch an English transcript
    let transcript = api.fetch_transcript(
        "dQw4w9WgXcQ",      // Video ID
        &["en"],            // Preferred languages
        false               // Don't preserve formatting
    ).await?;
     
    // Print each snippet of the transcript
    for snippet in transcript.parts() {
        println!("[{:.1}s]: {}", snippet.start, snippet.text);
    }
     
    Ok(())
}

Implementations§

Source§

impl YouTubeTranscriptApi

Source

pub fn new( cookie_path: Option<&Path>, proxy_config: Option<Box<dyn ProxyConfig + Send + Sync>>, http_client: Option<Client>, ) -> Result<Self, CookieError>

Creates a new YouTube Transcript API instance.

This method initializes an API instance with optional customizations for cookies, proxies, and HTTP client settings.

§Parameters
  • cookie_path - Optional path to a Netscape-format cookie file for authenticated requests
  • proxy_config - Optional proxy configuration for routing requests through a proxy service
  • http_client - Optional pre-configured HTTP client to use instead of the default one
§Returns
  • Result<Self, CookieError> - A new API instance or a cookie-related error
§Errors

This function will return an error if:

  • The cookie file exists but cannot be read or parsed
  • The cookie file is not in the expected Netscape format
§Examples
§Basic usage with default settings
let api = YouTubeTranscriptApi::new(None, None, None)?;
let cookie_path = Path::new("path/to/cookies.txt");
let api = YouTubeTranscriptApi::new(Some(&cookie_path), None, None)?;
§Using a proxy to bypass geographical restrictions
// Create a proxy configuration
let proxy = GenericProxyConfig::new(
    Some("http://proxy.example.com:8080".to_string()),
    None
)?;

let api = YouTubeTranscriptApi::new(
    None,
    Some(Box::new(proxy)),
    None
)?;
Source

pub async fn fetch_transcript( &self, video_id: &str, languages: &[&str], preserve_formatting: bool, ) -> Result<FetchedTranscript, CouldNotRetrieveTranscript>

Source

pub async fn list_transcripts( &self, video_id: &str, ) -> Result<TranscriptList, CouldNotRetrieveTranscript>

Source

pub async fn fetch_video_details( &self, video_id: &str, ) -> Result<VideoDetails, CouldNotRetrieveTranscript>

Source

pub async fn fetch_microformat( &self, video_id: &str, ) -> Result<MicroformatData, CouldNotRetrieveTranscript>

Source

pub async fn fetch_streaming_data( &self, video_id: &str, ) -> Result<StreamingData, CouldNotRetrieveTranscript>

Source

pub async fn fetch_video_infos( &self, video_id: &str, ) -> Result<VideoInfos, CouldNotRetrieveTranscript>

Fetches all available information about a YouTube video in a single request.

This method retrieves comprehensive information about a video in one network call, including:

  • Video details (title, author, etc.)
  • Microformat data (category, available countries, etc.)
  • Streaming data (available formats, qualities, etc.)
  • Transcript list (available caption languages)

This is more efficient than calling individual methods separately when multiple types of information are needed, as it avoids multiple HTTP requests.

§Parameters
  • video_id - The YouTube video ID (e.g., “dQw4w9WgXcQ”)
§Returns
  • Result<VideoInfos, CouldNotRetrieveTranscript> - Combined video information on success, or an error
§Errors

This method will return a CouldNotRetrieveTranscript error if:

  • The video doesn’t exist or is private
  • The video has geo-restrictions that prevent access
  • Network errors occur during the request
§Examples
let api = YouTubeTranscriptApi::new(None, None, None)?;
let video_id = "dQw4w9WgXcQ";

// Fetch all information in a single request
let infos = api.fetch_video_infos(video_id).await?;

// Access combined information
println!("Title: {}", infos.video_details.title);
println!("Author: {}", infos.video_details.author);

if let Some(category) = &infos.microformat.category {
    println!("Category: {}", category);
}

println!("Available formats: {}", infos.streaming_data.formats.len());
println!("Available transcripts: {}", infos.transcript_list.transcripts().count());

Trait Implementations§

Source§

impl Clone for YouTubeTranscriptApi

Source§

fn clone(&self) -> YouTubeTranscriptApi

Returns a duplicate of the value. Read more
1.0.0 · Source§

const fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T