Get Trending Videos via YouTube API

Test this app for free
242
import logging
import os
import requests
from fastapi import FastAPI, HTTPException
from fastapi.responses import RedirectResponse
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.get("/", include_in_schema=False)
def root():
    return RedirectResponse(url='/docs')

# Importing KeywordData class from youtube_trending_videos.py
from youtube_trending_videos import get_trending_videos

app.post("/trending/")(get_trending_videos)

if __name__ == "__main__":
Get full code

Frequently Asked Questions

What are some potential business applications for this YouTube Trending Videos API?

The Get Trending Videos via YouTube API template can be utilized in various business scenarios: - Content creators can use it to stay updated on trending topics and tailor their content accordingly. - Marketing teams can leverage it to identify popular themes for ad campaigns or influencer partnerships. - News organizations can quickly find trending videos related to current events. - E-commerce platforms can use it to showcase popular product review videos.

How can this API enhance user engagement on a website or app?

The Get Trending Videos via YouTube API can significantly boost user engagement by: - Providing a dynamic, always-updated section of trending content related to the user's interests. - Allowing users to discover popular videos without leaving your platform. - Enabling the creation of curated playlists based on trending topics. - Facilitating social sharing of trending content, potentially increasing viral reach.

What are the rate limit considerations when using this YouTube API integration?

When using the Get Trending Videos via YouTube API template, it's crucial to be aware of YouTube's API quotas: - The free tier typically allows for 10,000 units per day. - Each search request costs 100 units, and each video details request costs 1 unit per video. - To manage this, implement caching strategies and limit the frequency of API calls. - For high-volume applications, consider applying for higher quotas or using a YouTube API client library with built-in quota management.

How can I modify the API to search for trending videos in a specific country other than the US?

To search for trending videos in a different country, you can modify the regionCode parameter in the get_trending_videos function. Here's an example of how to change it to search for trending videos in Canada:

python def get_trending_videos(data: KeywordData): # ... (existing code) search_params = { "part": "snippet", "q": data.keywords, "key": api_key, "chart": "mostPopular", "regionCode": "CA", # Changed from "US" to "CA" for Canada "maxResults": 10, "type": "video" } # ... (rest of the function)

You can replace "CA" with any valid ISO 3166-1 alpha-2 country code to target different regions.

How can I extend the Get Trending Videos via YouTube API to include additional video information like view count or likes?

The template already fetches detailed video information, including statistics. To include view count and likes in the response, you can modify the get_trending_videos function to add this data to the videos_info list. Here's an example:

```python def get_trending_videos(data: KeywordData): # ... (existing code) videos_info = [] for item in r.json()['items']: video_data = { 'title': item['snippet']['title'], 'description': item['snippet']['description'], 'publishedAt': item['snippet']['publishedAt'], 'thumbnailUrl': item['snippet']['thumbnails']['high']['url'], 'videoUrl': f"https://www.youtube.com/watch?v={item['id']}", 'viewCount': item['statistics']['viewCount'], 'likeCount': item['statistics'].get('likeCount', 'N/A') } videos_info.append(video_data)

   return videos_info

```

This modification will include the view count and like count (if available) for each video in the API response.

Created: | Last Updated:

This app is provides fast api endpoint and is designed to fetch trending videos from YouTube based on keywords provided by the user. It utilizes the YouTube Data API v3 to search for videos that are currently trending in the US region. The app requires a valid YouTube API key, which must be set as an environment variable named `YOUTUBE_API_KEY`. The response includes detailed information about each video, including a direct link to the video on YouTube.

Introduction to the Template

Welcome to the "How to get trending videos for a specific keyword via YouTube API" template. This guide will walk you through the process of using this Lazy template to create an application that fetches trending videos from YouTube based on user-provided keywords. The application leverages the YouTube Data API v3 and is designed to be simple to use, even for non-technical builders.

Clicking Start with this Template

To begin, click on the "Start with this Template" button. This will initialize the template in the Lazy Builder interface, pre-populating the code necessary for the application.

Initial Setup: Adding Environment Secrets

Before testing the application, you 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 "YouTube Data API v3".
  • Enable the YouTube Data API v3 for your project.
  • Go to "Credentials" and click on "Create credentials". Select "API key" from the dropdown.
  • Copy the generated API key.
  • 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 the environment secret is set, press the "Test" button. This will deploy the application and launch the Lazy CLI. You will be provided with a server link to interact with the API.

Entering Input: Filling in User Input

If the application requires user input, the Lazy CLI will prompt you for it after pressing the test button. For this template, you will be asked to provide keywords for which you want to find trending YouTube videos.

Using the App

After deployment, you can use the provided server link to send requests to the API. Additionally, you will receive a link to the FastAPI documentation (`/docs`) where you can test the API endpoints directly from your browser.

Here's a sample request to the `/trending/` endpoint:

`POST /trending/
Content-Type: application/json

{
  "keywords": "music"
}` And a sample response might look like this:

[   {     "title": "Trending Music Video",     "description": "Latest trending music video on YouTube",     "videoUrl": "https://www.youtube.com/watch?v=example"     // ... other video details   }   // ... more videos ]

Integrating the App

If you wish to integrate this application with an external tool or service, you will need to use the server link provided by Lazy. For instance, you can add the API endpoint to a frontend application to display trending videos based on user input. Ensure that you handle the API key securely and do not expose it in the frontend.

For further integration, such as adding the app's server link in an external tool, follow the specific instructions provided by that tool for adding external API endpoints.

By following these steps, you should now have a fully functional application that can fetch trending YouTube videos based on keywords. Enjoy building with Lazy!



Here are 5 key business benefits for this template:

Template Benefits

  1. Real-time Market Insights: Businesses can quickly identify trending topics and content in their industry, allowing them to stay ahead of market trends and adjust their strategies accordingly.

  2. Content Strategy Optimization: By analyzing trending videos related to specific keywords, companies can refine their content creation strategy to align with current audience interests and preferences.

  3. Competitive Analysis: The template enables businesses to monitor their competitors' popular content, helping them understand what resonates with their target audience and identify gaps in their own content offerings.

  4. Influencer Identification: By tracking trending videos, companies can discover rising influencers in their niche, opening up opportunities for collaborations and partnerships.

  5. Ad Campaign Targeting: The ability to fetch trending videos based on keywords can help businesses identify optimal placement for their video ads, ensuring higher visibility and engagement rates.

Technologies

Similar templates