YouTube API Router
Relevant source files
The following files were used as context for generating this wiki page:
- apps/api/src/features/youtube/youtube.router.ts
- apps/api/src/features/youtube/youtube.service.ts
- apps/api/src/trpc/router.ts
- packages/types/src/youtube/youtube-video.type.ts
- apps/web/src/features/youtube/components/video-detail.component.tsx
- apps/web/src/features/search/views/video-search.view.tsx
- README.md
The youtubeRouter is a core component of the backend API (apps/api) responsible for handling all data fetching and interactions related to the YouTube Data API v3. It is implemented as a tRPC router, providing type-safe procedures that are consumed by the frontend React application (apps/web).
Following the project's feature-based architecture, the youtubeRouter separates concerns by defining the API endpoints in youtube.router.ts and encapsulating the business logic and external API calls within youtube.service.ts. This router is combined with other feature routers, such as the aiRouter, into a single appRouter that serves as the main entry point for all API requests. All procedures within this router are protected, meaning they require user authentication to be accessed.
Sources: README.md:15-23, 65-67, apps/api/src/features/youtube/youtube.router.ts, apps/api/src/trpc/router.ts:5-6
Architecture Overview
The youtubeRouter sits between the tRPC server and the business logic that communicates with the external YouTube API. This design creates a clear separation of concerns, where the router is a thin layer responsible only for defining procedures, inputs, and outputs.
This diagram illustrates the data flow from the client to the YouTube API through the youtubeRouter.
API Procedures
The youtubeRouter exposes several protectedProcedure endpoints for different YouTube-related actions.
Sources: apps/api/src/features/youtube/youtube.router.ts:11-48
resolveChannel
A mutation procedure that resolves a YouTube channel handle, name, or ID into a standardized channel ID.
| Type | Parameter | Zod Schema | Description |
|---|---|---|---|
| Input | identifier | z.string().min(1) | The channel handle (e.g., @handle), name, or ID. |
| Output | channelId | string | The resolved YouTube channel ID. |
Sources: apps/api/src/features/youtube/youtube.router.ts:13-17
getVideos
A query procedure that fetches a list of the most popular videos for a given channel ID.
| Type | Parameter | Zod Schema | Description |
|---|---|---|---|
| Input | channelId | z.string().min(1) | The YouTube channel ID. |
| Output | videos | YouTubeVideo[] | An array of video objects. |
Sources: apps/api/src/features/youtube/youtube.router.ts:22-26
getComments
A query procedure that fetches the top comments for a specific video.
| Type | Parameter | Zod Schema | Description |
|---|---|---|---|
| Input | videoId | z.string().min(1) | The YouTube video ID. |
| Output | comments | YouTubeComment[] | An array of comment objects. |
Sources: apps/api/src/features/youtube/youtube.router.ts:31-35
searchVideos
A query procedure that performs a global search for YouTube videos with sorting options.
| Type | Parameter | Zod Schema | Description |
|---|---|---|---|
| Input | (object) | videoSearchParamsSchema | An object containing the query, sort order, and max results. |
| Output | videos | YouTubeVideo[] | An array of video objects matching the search criteria. |
Sources: apps/api/src/features/youtube/youtube.router.ts:40-48
Core Services
The business logic for the router procedures is implemented in youtube.service.ts. These functions are responsible for constructing requests to the YouTube Data API, sending them, and formatting the responses. The base URL for all requests is https://www.googleapis.com/youtube/v3.
Sources: apps/api/src/features/youtube/youtube.service.ts:5
resolveChannelId(identifier)
This function implements a multi-step process to find a channel ID from a user-provided string.
The following flowchart shows the logic for resolving a channel identifier.
fetchChannelVideos(channelId) and searchVideos(query, ...)
These functions fetch video details and statistics. They follow a two-step process to gather all required information, as the YouTube API search endpoint does not return full statistics.
- Search: A request is made to the
/searchendpoint to get a list of video IDs, ordered byviewCountorrelevance. - Details: A second request is made to the
/videosendpoint with the collected video IDs to fetch detailed statistics likelikeCountandcommentCount.
The sequence diagram below illustrates this two-step fetch process.
For searchVideos, if the sort option is likes or comments (which are not supported for ordering in the YouTube API's search endpoint), the service fetches the videos ordered by relevance and then performs the sorting manually in the backend.
Sources: apps/api/src/features/youtube/youtube.service.ts:65-163, apps/api/src/features/youtube/youtube.service.ts:225-307
fetchVideoComments(videoId)
This function retrieves comments for a video by making a single call to the /commentThreads endpoint of the YouTube API. It fetches a maximum of 20 top-level comments.
Sources: apps/api/src/features/youtube/youtube.service.ts:168-201
Data Models
The router and services rely on shared types defined in the @repo/types package to ensure consistency between the frontend and backend.
YouTubeVideo
This is the primary data structure for representing a YouTube video within the application. The youtube.service.ts file is responsible for mapping the raw, complex response from the YouTube API into this clean, structured object.
The youtubeVideoSchema Zod object defines the shape of this type.
| Field | Type | Description |
|---|---|---|
id | string | The unique ID of the video. |
title | string | The title of the video. |
description | string | The description of the video. |
thumbnailUrl | string | The URL for the video's high-quality thumbnail. |
viewCount | string | The number of views. |
likeCount | string | The number of likes. |
commentCount | string | The number of comments. |
publishedAt | string | The ISO 8601 date string of when it was published. |
channelTitle | string | The title of the channel that posted the video. |
Sources: packages/types/src/youtube/youtube-video.type.ts:3-14, apps/api/src/features/youtube/youtube.service.ts:140-163
Client-Side Consumption
The frontend React application in apps/web uses a pre-configured tRPC client to call the procedures exposed by youtubeRouter.
For example, the VideoDetail component fetches comments for a video using the getComments query:
// Source: apps/web/src/features/youtube/components/video-detail.component.tsx:31-33
const { comments } = await trpcClient.youtube.getComments.query({
videoId: video.id,
});
Similarly, the VideoSearchView uses TanStack Query with the tRPC client to fetch search results:
// Source: apps/web/src/features/search/views/video-search.view.tsx:23-27
const { data, isLoading, error, refetch } = useQuery({
...trpc.youtube.searchVideos.queryOptions({
query: searchQuery,
sortBy,
maxResults: 20,
}),
enabled: !!searchQuery && hasSearched,
});
Sources: apps/web/src/features/youtube/components/video-detail.component.tsx:31-33, apps/web/src/features/search/views/video-search.view.tsx:23-27
Summary
The YouTube API Router is a well-structured and essential module that serves as the backend's dedicated interface for all YouTube data. By leveraging tRPC and a clear service-router pattern, it provides a robust, type-safe, and authenticated API for the frontend application. It effectively encapsulates the complexities of the external YouTube Data API, including multi-step data fetching and manual sorting, presenting a simplified and consistent data model to the rest of the application.