Documentation
¶
Overview ¶
Package youtubetranscript is the Go client for the YouTubeTranscript.net API.
client, err := youtubetranscript.NewClient() // reads YTT_API_KEY
if err != nil { log.Fatal(err) }
res, err := client.Transcripts.Get(ctx, "jNQXAC9IVRw", nil)
Only the standard library is used.
Index ¶
- Constants
- func Bool(v bool) *bool
- func Int(v int) *int
- type AccountService
- type Batch
- type BatchCounts
- type BatchCreateOptions
- type BatchDetail
- type BatchExportOptions
- type BatchGetOptions
- type BatchItem
- type BatchLimits
- type BatchRetryResult
- type BatchWaitOptions
- type BatchesService
- func (s *BatchesService) Create(ctx context.Context, opts *BatchCreateOptions) (*Batch, error)
- func (s *BatchesService) Delete(ctx context.Context, batchID string) (*Removed, error)
- func (s *BatchesService) Export(ctx context.Context, batchID string, opts *BatchExportOptions) ([]byte, error)
- func (s *BatchesService) Get(ctx context.Context, batchID string, opts *BatchGetOptions) (*BatchDetail, error)
- func (s *BatchesService) Retry(ctx context.Context, batchID string) (*BatchRetryResult, error)
- func (s *BatchesService) Wait(ctx context.Context, batchID string, opts *BatchWaitOptions) (*BatchDetail, error)
- type CaptionTrack
- type Chapter
- type Client
- type Credits
- type DeleteOptions
- type DownloadOptions
- type Error
- type FreeCredits
- type GetOptions
- type JobError
- type LibraryItem
- type Limits
- type ListOptions
- type Option
- type Removed
- type Segment
- type SubmitOptions
- type Transcript
- type TranscriptList
- type TranscriptResult
- type TranscriptsService
- func (s *TranscriptsService) Delete(ctx context.Context, videoID string, opts *DeleteOptions) (*Removed, error)
- func (s *TranscriptsService) Download(ctx context.Context, videoID string, opts *DownloadOptions) (string, error)
- func (s *TranscriptsService) Get(ctx context.Context, video string, opts *GetOptions) (*TranscriptResult, error)
- func (s *TranscriptsService) Info(ctx context.Context, video string) (*VideoInfo, error)
- func (s *TranscriptsService) Job(ctx context.Context, jobID string) (*TranscriptResult, error)
- func (s *TranscriptsService) List(ctx context.Context, opts *ListOptions) (*TranscriptList, error)
- func (s *TranscriptsService) Submit(ctx context.Context, video string, opts *SubmitOptions) (*TranscriptResult, error)
- type Usage
- type VideoInfo
- type VideoMetadata
Constants ¶
const ( // Version is the SDK version. Version = "0.1.0" // DefaultBaseURL is used when neither WithBaseURL nor YTT_BASE_URL is set. DefaultBaseURL = "https://api.youtubetranscript.net" // DefaultTimeout is the per-request HTTP timeout. DefaultTimeout = 60 * time.Second // DefaultMaxRetries is the number of automatic retries. DefaultMaxRetries = 2 )
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AccountService ¶
type AccountService struct {
// contains filtered or unexported fields
}
AccountService covers account information.
type Batch ¶
type Batch struct {
ID string `json:"id"`
Status string `json:"status"` // pending, processing, completed, failed
Name string `json:"name"`
SourceType string `json:"sourceType"`
Lang string `json:"lang"`
TotalCredits int `json:"totalCredits"`
Counts BatchCounts `json:"counts"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
}
Batch is a batch job.
type BatchCounts ¶
type BatchCounts struct {
Total int `json:"total"`
Pending int `json:"pending"`
Success int `json:"success"`
Failed int `json:"failed"`
}
BatchCounts are the per-status video counts of a batch.
type BatchCreateOptions ¶
type BatchCreateOptions struct {
// Items are video links (or ids).
Items []string
// Playlist is a playlist link or id.
Playlist string
// Channel is a channel link, @handle or id.
Channel string
// Language is a comma-separated priority list (default "auto").
Language string
// Limit caps the videos taken from a playlist or channel (1-500).
Limit int
// Name labels the batch (up to 200 characters).
Name string
}
BatchCreateOptions describes a batch. Set exactly one of Items, Playlist, Channel.
type BatchDetail ¶
type BatchDetail struct {
Batch Batch `json:"batch"`
Items []BatchItem `json:"items"`
NextPageToken string `json:"nextPageToken"`
}
BatchDetail is a batch with one page of its videos.
type BatchExportOptions ¶
type BatchExportOptions struct {
// Format is zip (default), csv, txt, json, srt or vtt.
Format string
// Files is the format of each file inside a zip: txt, srt, vtt, json or csv.
Files string
// Timestamps keeps timestamps; nil means the server default (true).
Timestamps *bool
}
BatchExportOptions are the optional parameters of Export.
type BatchGetOptions ¶
type BatchGetOptions struct {
// MaxResults is the page size (1-500); 0 means the server default.
MaxResults int
// PageToken continues from BatchDetail.NextPageToken.
PageToken string
}
BatchGetOptions are the optional parameters of Get.
type BatchItem ¶
type BatchItem struct {
ID string `json:"id"`
Platform string `json:"platform"`
ExternalID string `json:"externalId"`
SourceURL string `json:"sourceUrl"`
Lang string `json:"lang"`
Status string `json:"status"` // pending, processing, success, failed
Title string `json:"title"`
Channel string `json:"channel"`
DurationSec int `json:"durationSec"`
Words int `json:"words"`
Error string `json:"error"`
}
BatchItem is one video of a batch.
type BatchLimits ¶
type BatchLimits struct {
ItemsPerJob int `json:"itemsPerJob"`
}
BatchLimits are the batch limits of the account.
type BatchRetryResult ¶
type BatchRetryResult struct {
Batch Batch `json:"batch"`
Retried int `json:"retried"`
Credits int `json:"credits"`
}
BatchRetryResult is the answer of Batches.Retry.
type BatchWaitOptions ¶
type BatchWaitOptions struct {
// Timeout bounds the wait (default 1800s).
Timeout time.Duration
// PollInterval is the wait between polls (default 3s).
PollInterval time.Duration
}
BatchWaitOptions are the optional parameters of Wait.
type BatchesService ¶
type BatchesService struct {
// contains filtered or unexported fields
}
BatchesService covers batch jobs.
func (*BatchesService) Create ¶
func (s *BatchesService) Create(ctx context.Context, opts *BatchCreateOptions) (*Batch, error)
Create starts a batch (POST /v1/batch). It is never retried automatically: a repeated request would be charged twice. Giving none or more than one of Items, Playlist and Channel fails locally with INVALID_REQUEST.
func (*BatchesService) Export ¶
func (s *BatchesService) Export(ctx context.Context, batchID string, opts *BatchExportOptions) ([]byte, error)
Export downloads a batch (GET /v1/batch/{batchId}/export) and returns the raw bytes (a zip archive by default).
func (*BatchesService) Get ¶
func (s *BatchesService) Get(ctx context.Context, batchID string, opts *BatchGetOptions) (*BatchDetail, error)
Get returns a batch with one page of its videos (GET /v1/batch/{batchId}).
func (*BatchesService) Retry ¶
func (s *BatchesService) Retry(ctx context.Context, batchID string) (*BatchRetryResult, error)
Retry re-runs the failed videos of a finished batch (POST /v1/batch/{batchId}/retry). It is never retried automatically.
func (*BatchesService) Wait ¶
func (s *BatchesService) Wait(ctx context.Context, batchID string, opts *BatchWaitOptions) (*BatchDetail, error)
Wait polls Get until the batch status is "completed" or "failed" and returns the last result. Running past the timeout returns an *Error with code TIMEOUT. A 429 while polling waits for Retry-After and continues.
type CaptionTrack ¶
CaptionTrack describes one caption track.
type Client ¶
type Client struct {
// Transcripts covers transcript extraction, jobs, info and the library.
Transcripts *TranscriptsService
// Batches covers batch jobs.
Batches *BatchesService
// Account covers usage and limits.
Account *AccountService
// contains filtered or unexported fields
}
Client talks to the API. It is safe for concurrent use.
type Credits ¶
type Credits struct {
Balance int `json:"balance"`
FreeToday FreeCredits `json:"freeToday"`
Available int `json:"available"`
HasPurchased bool `json:"hasPurchased"`
}
Credits is the credit balance.
type DeleteOptions ¶
type DeleteOptions struct {
// Language removes one language only; empty uses the server default.
Language string
}
DeleteOptions are the optional parameters of Delete.
type DownloadOptions ¶
type DownloadOptions struct {
// Format is txt (default), srt, vtt, json or md.
Format string
// Language selects a saved language; empty means the latest.
Language string
}
DownloadOptions are the optional parameters of Download.
type Error ¶
type Error struct {
// Status is the HTTP status code; 0 for errors raised locally
// (API_KEY_REQUIRED, INVALID_REQUEST, TIMEOUT while polling, ...).
Status int
// Code is the server's error.code, or HTTP_<status> for non-JSON
// responses, NETWORK_ERROR for connection failures, TIMEOUT for timeouts.
Code string
// Message is the human readable message.
Message string
// RequestID is the X-Request-Id response header, when present.
RequestID string
// RetryAfter is the Retry-After response header; 0 when absent.
RetryAfter time.Duration
// Details is the server's error object as returned (for example
// availableLanguages, creditsRequired); nil for local errors.
Details map[string]any
// Retryable is true for 429, 5xx and NETWORK_ERROR.
Retryable bool
// JobID is set when the error belongs to a transcript job
// (a failed job or a polling TIMEOUT).
JobID string
// contains filtered or unexported fields
}
Error is the single error type returned by every method of this package. Extract it with errors.As:
var apiErr *youtubetranscript.Error
if errors.As(err, &apiErr) { fmt.Println(apiErr.Code, apiErr.Status) }
type FreeCredits ¶
type FreeCredits struct {
Limit int `json:"limit"`
Used int `json:"used"`
Remaining int `json:"remaining"`
ResetsAt string `json:"resetsAt"`
}
FreeCredits is today's free allowance.
type GetOptions ¶
type GetOptions struct {
// Language is a comma-separated priority list: BCP-47 codes, "auto",
// "asr" or "asr-<code>". Default "auto".
Language string
// Format is "json" (default) or "text".
Format string
// IncludeTimestamp keeps start/duration (json) or [m:ss] prefixes (text).
IncludeTimestamp *bool
// SendMetadata adds the Metadata object.
SendMetadata *bool
// ConfirmCredits accepts a cost above 10 credits.
ConfirmCredits *bool
// Timeout bounds the whole call including polling (default 300s).
Timeout time.Duration
// PollInterval is the wait between job polls (default 2s).
PollInterval time.Duration
}
GetOptions are the optional parameters of Get. Zero values mean "server default".
type LibraryItem ¶
type LibraryItem struct {
ID string `json:"id"`
Platform string `json:"platform"`
ExternalID string `json:"externalId"`
SourceURL string `json:"sourceUrl"`
Lang string `json:"lang"`
Title string `json:"title"`
Channel string `json:"channel"`
ThumbnailURL string `json:"thumbnailUrl"`
Words int `json:"words"`
DurationSec int `json:"durationSec"`
Starred bool `json:"starred"`
Origin string `json:"origin"`
CreatedAt string `json:"createdAt"`
}
LibraryItem is one row of the transcript library.
type Limits ¶
type Limits struct {
TaskConcurrency int `json:"taskConcurrency"`
ActiveTasks int `json:"activeTasks"`
}
Limits are the concurrency limits of the account.
type ListOptions ¶
type ListOptions struct {
// Q searches titles and channels.
Q string
// Lang filters by language.
Lang string
// Sort is "recent" (default), "oldest" or "title".
Sort string
// Page starts at 1; 0 means the server default.
Page int
// PageSize is 1-100; 0 means the server default (24).
PageSize int
}
ListOptions are the optional parameters of List.
type Option ¶
type Option func(*config)
Option configures NewClient.
func WithAPIKey ¶
WithAPIKey sets the API key (default: the YTT_API_KEY environment variable).
func WithBaseURL ¶
WithBaseURL sets the API origin (default: YTT_BASE_URL, then DefaultBaseURL). Trailing slashes are removed.
func WithHTTPClient ¶
WithHTTPClient replaces the underlying *http.Client (proxies, custom transports). Per-request timeouts are applied with contexts, so the client's own Timeout can stay zero.
func WithMaxRetries ¶
WithMaxRetries sets how many times a retryable request is retried (default 2; 0 disables retries).
func WithTimeout ¶
WithTimeout sets the timeout of a single HTTP request (default 60s).
type Removed ¶
type Removed struct {
Removed bool `json:"removed"`
}
Removed is the answer of the delete calls.
type Segment ¶
type Segment struct {
Text string `json:"text"`
Start float64 `json:"start"`
Duration float64 `json:"duration"`
}
Segment is one caption line. Start and Duration are in seconds.
type SubmitOptions ¶
type SubmitOptions struct {
Language string
Format string
IncludeTimestamp *bool
SendMetadata *bool
ConfirmCredits *bool
// WaitMs is how long the server may hold the request for a fast result
// before answering 202 (0-10000). Nil sends no value (server default).
WaitMs *int
}
SubmitOptions are the optional parameters of Submit.
type Transcript ¶
type Transcript struct {
ID string `json:"id"`
Platform string `json:"platform"`
ExternalID string `json:"externalId"`
SourceURL string `json:"sourceUrl"`
Lang string `json:"lang"`
Origin string `json:"origin"` // original, auto or asr
Title string `json:"title"`
Channel string `json:"channel"`
ThumbnailURL string `json:"thumbnailUrl"`
DurationSec int `json:"durationSec"`
PublishedAt string `json:"publishedAt"`
Segments []Segment `json:"segments"`
CreatedAt string `json:"createdAt"`
}
Transcript is a saved transcript.
type TranscriptList ¶
type TranscriptList struct {
Transcripts []LibraryItem `json:"transcripts"`
Total int `json:"total"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
Langs []string `json:"langs"`
}
TranscriptList is one page of the library.
type TranscriptResult ¶
type TranscriptResult struct {
Status string `json:"status"`
JobID string `json:"jobId"`
Stage string `json:"stage"`
Cached bool `json:"cached"`
Language string `json:"language"`
Format string `json:"format"` // json or text
MetadataStatus string `json:"metadataStatus"`
LengthSeconds int `json:"lengthSeconds"`
LengthText string `json:"lengthText"`
Metadata *VideoMetadata `json:"metadata"`
// Transcript is set when Format is "json".
Transcript *Transcript `json:"transcript"`
// Text is set when Format is "text".
Text string `json:"text"`
Error *JobError `json:"error"`
// Raw is the original JSON response body.
Raw json.RawMessage `json:"-"`
}
TranscriptResult is either a finished transcript (Status "success") or a job still running (Status "pending" or "processing", with JobID). Unknown fields are ignored; Raw keeps the complete response body.
func (*TranscriptResult) Done ¶
func (r *TranscriptResult) Done() bool
Done reports whether the transcript is ready.
type TranscriptsService ¶
type TranscriptsService struct {
// contains filtered or unexported fields
}
TranscriptsService covers transcripts and the transcript library.
func (*TranscriptsService) Delete ¶
func (s *TranscriptsService) Delete(ctx context.Context, videoID string, opts *DeleteOptions) (*Removed, error)
Delete removes a transcript from the library (DELETE /v1/library/transcripts/youtube/{videoId}).
func (*TranscriptsService) Download ¶
func (s *TranscriptsService) Download(ctx context.Context, videoID string, opts *DownloadOptions) (string, error)
Download returns a saved transcript as text in the given format (GET /v1/library/transcripts/youtube/{videoId}/download). JSON is returned as a string too.
func (*TranscriptsService) Get ¶
func (s *TranscriptsService) Get(ctx context.Context, video string, opts *GetOptions) (*TranscriptResult, error)
Get returns the transcript of a video, polling the job when the server answers 202. A failed job returns an *Error (code from the job's error.code, else TRANSCRIPT_FAILED); running past opts.Timeout returns an *Error with code TIMEOUT and the JobID.
func (*TranscriptsService) Info ¶
Info returns the video details and caption languages; it is free (GET /v1/transcript/info).
func (*TranscriptsService) Job ¶
func (s *TranscriptsService) Job(ctx context.Context, jobID string) (*TranscriptResult, error)
Job returns a transcript job as the server reports it (GET /v1/transcript/job/{jobId}).
func (*TranscriptsService) List ¶
func (s *TranscriptsService) List(ctx context.Context, opts *ListOptions) (*TranscriptList, error)
List returns one page of the transcript library (GET /v1/library/transcripts).
func (*TranscriptsService) Submit ¶
func (s *TranscriptsService) Submit(ctx context.Context, video string, opts *SubmitOptions) (*TranscriptResult, error)
Submit sends the request once (with an Idempotency-Key) and returns the first response as is: a finished transcript (Status "success") or a job (Status "pending"/"processing" with JobID) to follow with Job. video is a watch / youtu.be / Shorts link or an 11 character video id.
type Usage ¶
type Usage struct {
Credits Credits `json:"credits"`
Batch BatchLimits `json:"batch"`
Limits Limits `json:"limits"`
// Raw is the original JSON response body.
Raw json.RawMessage `json:"-"`
}
Usage is the answer of Account.Usage.
type VideoInfo ¶
type VideoInfo struct {
Platform string `json:"platform"`
ExternalID string `json:"externalId"`
Title string `json:"title"`
Channel string `json:"channel"`
ChannelID string `json:"channelId"`
ThumbnailURL string `json:"thumbnailUrl"`
LengthSeconds int `json:"lengthSeconds"`
LengthText string `json:"lengthText"`
PublishedAt string `json:"publishedAt"`
Description string `json:"description"`
Chapters []Chapter `json:"chapters"`
AvailableLanguages []string `json:"availableLanguages"`
CaptionTracks []CaptionTrack `json:"captionTracks"`
SourceURL string `json:"sourceUrl"`
}
VideoInfo is the free video lookup.
type VideoMetadata ¶
type VideoMetadata struct {
Platform string `json:"platform"`
ExternalID string `json:"externalId"`
SourceURL string `json:"sourceUrl"`
Title string `json:"title"`
Channel string `json:"channel"`
ThumbnailURL string `json:"thumbnailUrl"`
PublishedAt string `json:"publishedAt"`
LengthSeconds int `json:"lengthSeconds"`
Language string `json:"language"`
}
VideoMetadata is returned when SendMetadata is set.