如何处理存在依赖关系的并发HTTP请求?基于YouTube API场景
Got it, let's break down exactly how to fetch the latest videos from your subscribed YouTube channels using the API. This is a chained process where each request relies on data from the last one, so we’ll go through each call in order and handle the list data properly.
First, you need to pull the list of channels you’re subscribed to using the GET /subscriptions/list endpoint.
Required Parameters:
part: Set tosnippet,subscriberSnippet(we need thechannelIdfrom each subscription entry)mine: Set totrue(this tells the API to return your subscriptions—note: this requires OAuth 2.0 authorization, since it’s user-specific private data)maxResults: Optional, but limit it (e.g.,50) to avoid hitting quota limits too quickly
What You’ll Extract:
From each item in the response’s items array, grab snippet.resourceId.channelId—this is the unique ID for each subscribed channel you’ll need next.
Every YouTube channel has a dedicated "uploads" playlist that stores all its videos (sorted by latest first). We need these playlist IDs using the GET /channels/list endpoint.
Required Parameters:
part: Set tocontentDetailsid: Pass a comma-separated string of all thechannelIds you collected in Step 1 (batch processing here saves API calls and quota)
What You’ll Extract:
For each channel in the response, pull contentDetails.relatedPlaylists.uploads—this is the playlist ID we’ll use to fetch the channel’s latest videos.
Now, for each uploads playlist ID, call GET /playlistItems/list to get the most recent video entries.
Required Parameters:
part: Set tosnippetplaylistId: The uploads playlist ID from Step 2maxResults: Number of latest videos you want per channel (e.g.,5)
What You’ll Extract:
From each playlist item, grab snippet.resourceId.videoId—this is the unique ID for each individual video.
Finally, batch all the videoIds you collected and call GET /videos/list to get complete metadata for each video.
Required Parameters:
part: Set tosnippet,contentDetails,statistics(adjust based on what data you need—title, publish date, duration, view count, etc.)id: Comma-separated string of allvideoIds from Step 3
What You’ll Get:
The response will include all the video data you need. You can sort the results by snippet.publishedAt to get the absolute latest videos across all your subscribed channels.
Key Tips to Avoid Headaches:
- OAuth 2.0 Authorization: Since you’re accessing user-specific subscriptions, you’ll need to authenticate with an OAuth token that has the
https://www.googleapis.com/auth/youtube.readonlyscope. - Pagination: If you have more than 50 subscriptions or more than 50 videos in a playlist, the API will return a
nextPageToken—you’ll need to make follow-up calls with this token to retrieve all results. - Quota Limits: YouTube API has daily quota limits (10,000 units). Batch requests (passing multiple IDs in one call) use fewer units than individual calls, so prioritize this to stay under the limit.
Simplified Python Example:
import requests # Replace with your valid OAuth token OAUTH_TOKEN = "your-oauth-token-here" headers = {"Authorization": f"Bearer {OAUTH_TOKEN}"} # Step 1: Fetch subscribed channel IDs subs_response = requests.get( "https://www.googleapis.com/youtube/v3/subscriptions", params={"part": "snippet", "mine": "true", "maxResults": 50}, headers=headers ) channel_ids = [item["snippet"]["resourceId"]["channelId"] for item in subs_response.json()["items"]] # Step 2: Fetch upload playlist IDs for each channel channels_response = requests.get( "https://www.googleapis.com/youtube/v3/channels", params={"part": "contentDetails", "id": ",".join(channel_ids)}, headers=headers ) upload_playlist_ids = [ item["contentDetails"]["relatedPlaylists"]["uploads"] for item in channels_response.json()["items"] ] # Step 3: Collect latest video IDs from each upload playlist video_ids = [] for playlist_id in upload_playlist_ids: playlist_response = requests.get( "https://www.googleapis.com/youtube/v3/playlistItems", params={"part": "snippet", "playlistId": playlist_id, "maxResults": 5}, headers=headers ) video_ids.extend([ item["snippet"]["resourceId"]["videoId"] for item in playlist_response.json()["items"] ]) # Step 4: Fetch full video details and sort by publish date videos_response = requests.get( "https://www.googleapis.com/youtube/v3/videos", params={"part": "snippet,statistics", "id": ",".join(video_ids)}, headers=headers ) videos = sorted( videos_response.json()["items"], key=lambda x: x["snippet"]["publishedAt"], reverse=True ) # Print the 10 latest videos for idx, video in enumerate(videos[:10], 1): print(f"{idx}. {video['snippet']['title']}") print(f" Published: {video['snippet']['publishedAt'][:10]}") print(f" Views: {video['statistics']['viewCount']}\n")
内容的提问来源于stack exchange,提问作者Marcos Tanaka

