Notifications
Clear all
To write a script to show results from youtube API 3.0 and need all HTML code, and a search box to show data, like title, thumbnail, duration, user, etc.
Here is the code example:
Â
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script>
function search() {
// Get the search query from the input field
var query = document.getElementById("search").value;
// Make a request to the YouTube API with the search query
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: query,
maxResults: 20
});
// Execute the request and handle the response
request.execute(function(response) {
var results = response.result;
var output = "";
// Loop through the results and build the HTML output
for (var i = 0; i < results.items.length; i++) {
var item = results.items[i];
output += "<div class='col-sm-6 col-md-4'>";
output += "<div class='card mb-4'>";
output += "<img class='card-img-top' src='" + item.snippet.thumbnails.default.url + "'>";
output += "<div class='card-body'>";
output += "<h5 class='card-title'>" + item.snippet.title + "</h5>";
output += "<p class='card-text'>By: " + item.snippet.channelTitle + "</p>";
output += "</div>";
output += "</div>";
output += "</div>";
}
// Update the HTML on the page with the search results
document.getElementById("results").innerHTML = output;
});
}
</script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="#">YouTube API Search</a>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" id="search" placeholder="Search for videos" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" onclick="search()">Search</button>
</form>
</div>
</nav>
<div class="container">
<div class="row" id="results"></div>
</div>
<script src="https://apis.google.com/js/api.js"></script>
<script>
gapi.load("client", function() {
gapi.client.setApiKey("API_KEY");
gapi.client.load("youtube", "v3", function() {});
});
</script>
</body>
</html>
Â
Note: In the script, you will need to replace API_KEY with your actual API key for the YouTube API. You can obtain an API key by creating a project in the Google Cloud Console and enabling the YouTube API.
Â
Jayanta DK
Topic starter
Posted : 12/02/2023 9:29 am
Community Forum
We’re currently working on improving our forum experience.
Submit a Guest Post →
We review all submissions before publishing.