YouTube API Search Guide
February 1, 2025 · AI Conversations
### 1. Set Up Google Cloud Project
– Go to the [Google Cloud Console](https://console.cloud.google.com/).
– Create a new project or select an existing one.
– Navigate to the **APIs & Services** dashboard and enable the **YouTube Data API v3**.
### 2. Create API Key
– In the same dashboard, go to **Credentials**.
– Click on **Create Credentials** and choose **API Key**.
– Copy the generated API key; you will need it for your API requests.
### 3. Make API Request
You can perform a search for YouTube videos using the following endpoint:
GET https://www.googleapis.com/youtube/v3/search
### 4. Sample Request
Here’s a sample request to search for videos:
GET https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&q=SEARCH_QUERY&type=video&key=YOUR_API_KEY
– **Parameters**:
– `part`: Specifies the resource parts to be included in the response (e.g., `snippet`).
– `maxResults`: Maximum number of results to return (default is 5, maximum is 50).
– `q`: The search query term (replace `SEARCH_QUERY` with your desired search term).
– `type`: The type of resource to search for (e.g., `video`).
– `key`: Your API key.
### 5. Sample Response
A successful response will return a JSON object containing the search results. Here's an example of what the response might look like:
{
"kind": "youtube#searchListResponse",
"etag": "etag_value",
"nextPageToken": "next_page_token",
"regionCode": "US",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": 10
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "etag_value",
"id": {
"kind": "youtube#video",
"videoId": "VIDEO_ID"
},
"snippet": {
"publishedAt": "2022-01-01T00:00:00Z",
"channelId": "CHANNEL_ID",
"title": "Video Title",
"description": "Video Description",
"thumbnails": {
"default": {
"url": "thumbnail_url",
"width": 120,
"height": 90
}
},
"channelTitle": "Channel Title",
"liveBroadcastContent": "none",
"publishTime": "2022-01-01T00:00:00Z"
}
}
]
}
### 6. Example Code (JavaScript)
Here's a simple example using JavaScript and the Fetch API:
const apiKey = 'YOUR_API_KEY';
const searchQuery = 'SEARCH_QUERY';
const url = `https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&q=${encodeURIComponent(searchQuery)}&type=video&key=${apiKey}`;
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
### Notes
– Make sure to replace `YOUR_API_KEY` with your actual API key.
– Replace `SEARCH_QUERY` with the term you want to search for.
This setup will allow you to search for YouTube videos programmatically using the YouTube Data API.
### Step 1: Set Up Laravel Backend
1. **Install GuzzleHTTP (if not already installed)**:
GuzzleHTTP is a PHP HTTP client that can be used to make API requests.
composer require guzzlehttp/guzzle
2. **Create a Controller**:
Create a controller that will handle the API requests to YouTube.
php artisan make:controller YouTubeController
3. **Implement the API Request**:
In `YouTubeController.php`, add a method to fetch videos from YouTube using the API.
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use GuzzleHttpClient;
class YouTubeController extends Controller
{
public function search(Request $request)
{
$apiKey = env('YOUTUBE_API_KEY'); // Store your API key in the .env file
$query = $request->input('query');
$client = new Client();
$response = $client->get("https://www.googleapis.com/youtube/v3/search", [
'query' => [
'part' => 'snippet',
'maxResults' => 10,
'q' => $query,
'type' => 'video',
'key' => $apiKey,
],
]);
return json_decode($response->getBody(), true);
}
}
4. **Add a Route**:
In `routes/web.php`, add a route for the search method.
use AppHttpControllersYouTubeController;
Route::get('/youtube/search', [YouTubeController::class, 'search']);
5. **Add API Key to .env**:
Store your YouTube API key in your `.env` file.
YOUTUBE_API_KEY=your_youtube_api_key_here
### Step 2: Set Up React Frontend
1. **Create a Search Component**:
Create a React component to handle the search input and display results.
// resources/js/Pages/YouTubeSearch.jsx
import React, { useState } from 'react';
import { Inertia } from '@inertiajs/inertia';
const YouTubeSearch = () => {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const handleSearch = (e) => {
e.preventDefault();
Inertia.get('/youtube/search', { query }, {
onSuccess: (page) => {
setResults(page.props.results);
},
});
};
return (
<div>
<form onSubmit={handleSearch}>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search YouTube"
/>
<button type="submit">Search</button>
</form>
<ul>
{results.map((item) => (
<li key={item.id.videoId}>
<h3>{item.snippet.title}</h3>
<img src={item.snippet.thumbnails.default.url} alt={item.snippet.title} />
<p>{item.snippet.description}</p>
</li>
))}
</ul>
</div>
);
};
export default YouTubeSearch;
2. **Render the Component**:
Ensure your React component is rendered in a page in your Laravel application. For example, in `resources/js/app.jsx`, you can render the component:
import React from 'react';
import ReactDOM from 'react-dom';
import YouTubeSearch from './Pages/YouTubeSearch';
const App = () => {
return (
<div>
<YouTubeSearch />
</div>
);
};
ReactDOM.render(<App />, document.getElementById('app'));
### Step 3: Test Your Application
1. **Run Your Laravel Application**:
php artisan serve
2. **Run Your Frontend Build**:
If you're using Vite, run:
npm run dev
3. **Visit Your Application**:
Open your browser and go to the URL where your Laravel app is running. You should see the search input for YouTube. Enter a search term and submit the form to see the results.
### Conclusion
This setup allows you to search for YouTube videos using the YouTube Data API in a Laravel application with a React frontend and Inertia.js for navigation. You can enhance the search results display and error handling as needed for your application.
### Step 1: Update Your Search Component
Modify the `YouTubeSearch` component to include functionality for playing a video when a user clicks on a search result.
// resources/js/Pages/YouTubeSearch.jsx
import React, { useState } from 'react';
import { Inertia } from '@inertiajs/inertia';
const YouTubeSearch = () => {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const [selectedVideoId, setSelectedVideoId] = useState(null);
const handleSearch = (e) => {
e.preventDefault();
Inertia.get('/youtube/search', { query }, {
onSuccess: (page) => {
setResults(page.props.results);
},
});
};
const handleVideoSelect = (videoId) => {
setSelectedVideoId(videoId);
};
const handleCloseVideo = () => {
setSelectedVideoId(null);
};
return (
<div>
<form onSubmit={handleSearch}>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search YouTube"
/>
<button type="submit">Search</button>
</form>
<ul>
{results.map((item) => (
<li key={item.id.videoId} onClick={() => handleVideoSelect(item.id.videoId)}>
<h3>{item.snippet.title}</h3>
<img src={item.snippet.thumbnails.default.url} alt={item.snippet.title} />
<p>{item.snippet.description}</p>
</li>
))}
</ul>
{selectedVideoId && (
<div className="video-modal">
<div className="video-overlay" onClick={handleCloseVideo}></div>
<div className="video-content">
<iframe
width="560"
height="315"
src={`https://www.youtube.com/embed/${selectedVideoId}`}
title="YouTube Video Player"
frameBorder="0"
allowFullScreen
></iframe>
<button onClick={handleCloseVideo}>Close</button>
</div>
</div>
)}
</div>
);
};
export default YouTubeSearch;
### Step 2: Add Basic Styles
You can add some basic styles for the video modal in your CSS file to improve its appearance:
/* resources/css/app.css */
.video-modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.8);
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
}
.video-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
cursor: pointer;
}
.video-content {
position: relative;
background: white;
padding: 20px;
border-radius: 8px;
z-index: 1000;
}
### Step 3: Run Your Application
1. **Run Your Laravel Application**:
php artisan serve
2. **Run Your Frontend Build**:
If you're using Vite, run:
npm run dev
3. **Visit Your Application**:
Open your browser and go to the URL where your Laravel app is running. Enter a search term, and after clicking on a video in the search results, the video should play in a modal overlay.
### Explanation of the Code
– **State Management**:
– `selectedVideoId`: This state stores the ID of the video to be played.
– **Video Selection**:
– The `handleVideoSelect` function sets the selected video ID, and the modal opens to show the video.
– **Modal Close**:
– Clicking the overlay or the close button will call `handleCloseVideo`, which resets the `selectedVideoId`, effectively closing the modal.
– **YouTube Iframe**:
– The `iframe` element is used to embed the YouTube player. It uses the selected video ID to play the correct video.
This setup allows users to search for YouTube videos, display the results, and play a selected video in a modal overlay, enhancing the user experience.