Get Latest Video from Channel via YouTube API

Test this app for free
80
import logging
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from youtube_api_handler import get_latest_video, ChannelInput
from some_get_request_handler import handle_get_endpoint
from some_post_request_handler import handle_post_endpoint, Data

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.WARNING)

app = FastAPI()

@app.post("/latest-video/")
def latest_video(channel_input: ChannelInput):
    try:
        video_info = get_latest_video(channel_input)
        return JSONResponse(status_code=200, content=video_info)
    except Exception as e:
        logger.error(f"Failed to fetch video information: {e}")
        raise HTTPException(status_code=500, detail="Failed to fetch video information.")
    except Exception as e:
        logger.error(f"Failed to fetch latest video: {e}")
        raise HTTPException(status_code=500, detail="Failed to fetch latest video.")
Get full code

Frequently Asked Questions

How can businesses use this YouTube API template to enhance their content strategy?

The Get Latest Video from Channel via YouTube API template can be a valuable tool for businesses looking to stay updated on competitor content or track industry influencers. By easily retrieving the latest video details from specific channels, companies can: - Monitor competitor video releases and adjust their content strategy accordingly - Keep track of industry trends by following thought leaders' latest uploads - Automate the process of curating relevant content for social media sharing or newsletter inclusion

What are some potential applications of this template in the marketing industry?

In the marketing industry, the Get Latest Video from Channel via YouTube API template can be utilized for: - Creating a dashboard that displays the latest videos from multiple influencer channels for easy campaign monitoring - Automating the process of embedding the newest product review videos on an e-commerce website - Developing a content aggregator that compiles the latest videos from various industry-specific channels for market research purposes

How can educational institutions benefit from implementing this YouTube API template?

Educational institutions can leverage the Get Latest Video from Channel via YouTube API template to: - Automatically update course pages with the latest lecture videos from professors' channels - Create a centralized hub for student organizations to showcase their most recent video content - Develop a system that notifies students when new educational content is uploaded to relevant channels

How can I modify the template to retrieve multiple videos instead of just the latest one?

To retrieve multiple videos, you can modify the get_latest_video function in the youtube_api_handler.py file. Here's an example of how to fetch the 5 most recent videos:

```python def get_latest_videos(channel_input: ChannelInput, max_results: int = 5) -> list: # ... (existing channel ID extraction code) ...

   params = {
       "part": "snippet",
       "channelId": channel_id,
       "maxResults": max_results,
       "order": "date",
       "type": "video",
       "key": api_key
   }

   # ... (existing API request code) ...

   return data.get("items", [])

```

Then, update the FastAPI endpoint in main.py:

python @app.post("/latest-videos/") def latest_videos(channel_input: ChannelInput, max_results: int = 5): try: videos_info = get_latest_videos(channel_input, max_results) return JSONResponse(status_code=200, content=videos_info) except Exception as e: logger.error(f"Failed to fetch videos information: {e}") raise HTTPException(status_code=500, detail="Failed to fetch videos information.")

How can I add error handling for rate limiting in the YouTube API requests?

To handle rate limiting errors from the YouTube API, you can add a retry mechanism with exponential backoff. Here's an example of how to modify the API request in the get_latest_video function:

```python import time from requests.exceptions import HTTPError

def get_latest_video(channel_input: ChannelInput) -> dict: # ... (existing code) ...

   max_retries = 3
   retry_delay = 1

   for attempt in range(max_retries):
       try:
           response = requests.get(base_url, params=params)
           response.raise_for_status()
           break
       except HTTPError as e:
           if e.response.status_code == 429 and attempt < max_retries - 1:
               logger.warning(f"Rate limit exceeded. Retrying in {retry_delay} seconds...")
               time.sleep(retry_delay)
               retry_delay *= 2
           else:
               logger.error(f"Failed to fetch video information: {e}")
               raise ValueError("Failed to fetch video information.")

   # ... (rest of the existing code) ...

```

This modification adds a retry mechanism to the Get Latest Video from Channel via YouTube API template, helping to handle rate limiting errors more gracefully.

Created: | Last Updated:

A FastAPI-based application that retrieves the latest video details from your favorite channels using the YouTube API. Simply provide a channel ID or URL to get comprehensive results, including video ID, title, and description. The app requires a YouTube API key, which can be set as an environment variable.

Introduction to the Template

Welcome to the "How to get the latest video from a channel via YouTube API" template guide. This template is designed to help you create a FastAPI-based application that retrieves the latest video details from a YouTube channel. You'll be able to get the video ID, title, and description by providing a channel ID or URL. This guide will walk you through the steps to use this template on the Lazy platform.

Clicking Start with this Template

To begin using this template, click on the "Start with this Template" button. This will pre-populate the code in the Lazy Builder interface, so you won't need to copy, paste, or delete any code manually.

Initial Setup

Before you can use this template, you'll need to set up an environment secret for the YouTube API key. Here's how to obtain and set up your YouTube API key:

  • Go to the Google Developers Console (https://console.developers.google.com/).
  • Create a new project or select an existing one.
  • Click on "Enable APIs and Services" and search for the YouTube Data API v3.
  • Enable the YouTube Data API v3 for your project.
  • Go to "Credentials" and click on "Create credentials". Select "API key" and then copy the generated key.
  • Back in the Lazy Builder interface, navigate to the Environment Secrets tab.
  • Create a new secret with the key `YOUTUBE_API_KEY` and paste the API key you copied as the value.

Test: Pressing the Test Button

Once you have set up your YouTube API key in the environment secrets, press the "Test" button to deploy the app. The Lazy CLI will handle the deployment, and you won't need to worry about installing libraries or setting up your environment.

Entering Input

After pressing the "Test" button and once the app is deployed, the Lazy App's CLI interface will appear. If the code requires user input, you will be prompted to provide it there. For this template, you will need to input the channel ID or URL when prompted by the CLI.

Using the App

After deployment, Lazy will provide you with a dedicated server link to use the API. You can make requests to the `/latest-video/` endpoint to retrieve the latest video from the specified YouTube channel. Additionally, you will be provided with a link to the FastAPI documentation at `/docs` where you can test the API endpoints directly from your browser.

Here's a sample request you might make to the API:

`POST /latest-video/
Content-Type: application/json

{
  "channel_id_or_url": "UC_x5XG1OV2P6uZZ5FSM9Ttw"
}` And a sample response you might receive:

{   "video_id": "dQw4w9WgXcQ",   "title": "Rick Astley - Never Gonna Give You Up",   "description": "The official video for “Never Gonna Give You Up” by Rick Astley..." }

Integrating the App

If you wish to integrate this app with an external tool or service, you may need to add the app's server link provided by Lazy to that tool. For example, if you're building a website that displays the latest video from a YouTube channel, you would make an API call to the server link from your website's backend to retrieve the video details.

Remember, this template is designed to work seamlessly on the Lazy platform, so all the heavy lifting of deployment and environment management is taken care of for you. Enjoy building your application!



Here are 5 key business benefits for this template:

Template Benefits

  1. Automated Content Monitoring: Businesses can easily track the latest uploads from competitors, partners, or industry influencers, enabling quick responses to new content and trends.

  2. Social Media Management: Social media teams can instantly access the newest videos from specific channels, streamlining content curation and sharing processes across platforms.

  3. Marketing Campaign Tracking: Marketers can effortlessly monitor the latest video releases from sponsored channels or brand ambassadors, ensuring timely promotion and engagement with new content.

  4. Content Aggregation for News Platforms: News websites or content aggregators can automatically fetch and display the most recent videos from various news channels, keeping their platforms up-to-date with minimal manual effort.

  5. API Integration for Custom Applications: Developers can easily integrate this functionality into larger applications or dashboards, providing real-time YouTube data for diverse business needs such as market research, competitor analysis, or content recommendation systems.

Technologies

Similar templates