youtube api to upload videos from your website
Recently one of our readers asked how to get a list of videos on a YouTube channel? They wanted to prove a list of their videos in tabular format. In this article, we study how to apply YouTube API to get a list of YouTube videos from your aqueduct.
A user tin see all their videos on the YouTube website itself. Just if yous want to share the video list with someone else then yous have to keep this information offline. On the other hand, some users may want to display a video listing on their website.
That existence said, allow's have a look at how to get a list of YouTube videos using the YouTube API.
Note: Using the code of this article you lot can get a listing of videos of whatever YouTube channel providing a valid YouTube channel id.
Get Your API Cardinal
To get started with the YouTube API, y'all first demand to create an API primal from your Google account. This central is necessary while interacting with the YouTube APIs. The API call volition not succeed unless you pass the valid API key in each asking. Without an API key, YouTube considers all incoming requests as unauthorized.
Follow the steps beneath to create an API Fundamental.
- Get to the Google Developer Panel.
- Create a new project. You can also select the existing project.
- Type a proper name of your project. Google Panel will create a unique project ID.
- After creating a project, it will announced on top of the left sidebar.
- Click on Library. Y'all will run into a list of Google APIs.
- Search for YouTube Data API and enable information technology.
- Click on the Credentials. Select API central under Create credentials.
- Re-create the API key. We volition crave it in the next footstep.
Get a Listing of YouTube Videos
In one case y'all are ready with the API primal, create 3 files in your project. These files stand for configuration, helper methods, Ajax treatment, and brandish the terminal result.
-
config.php: In this file we prepare the API key as a constant. Information technology also has a helper method which gives an API telephone call and returns a response. -
ajax.php: This file will call the API to get the side by side set of results. -
index.php: It contains a form to enter YouTube channel id, requite an Ajax, and displays the video list.
In the config.php file, let's declare the API key as a constant variable. I'd as well ascertain the helper method which volition interact with the API endpoint.
<?php define('GOOGLE_API_KEY', 'PASTE_YOUR_API_KEY'); function getYTList($api_url = '') { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, truthful); $response = curl_exec($ch); $arr_result = json_decode($response); if (isset($arr_result->items)) { return $arr_result; } elseif (isset($arr_result->error)) { //var_dump($arr_result); //this line gives y'all error info if yous are non getting a video list. } } Make sure to replace the placeholder with the actual API fundamental. To execute the API call, you should have the cURL extension enabled on your server.
Create a Form
Next, create a uncomplicated grade where you tin enter the YouTube channel id and number of videos to render. YouTube API returns a maximum of fifty videos at a time.
<form method="get"> <p><input blazon="text" name="channel" placeholder="Enter Channel ID" value="<?php if(array_key_exists('channel', $_GET)) repeat $_GET['channel']; ?>" required></p> <p><input blazon="number" name="max_result" placeholder="Max Results" min="1" max="l" value="<?php if(array_key_exists('max_result', $_GET)) echo $_GET['max_result']; ?>" required></p> <p><input type="submit" value="Submit"></p> </form> I set the form method as Get. Upon form submission, information technology will ship channel id and max_result via Become parameter. And so on the superlative of the same file, I will write the lawmaking as follows:
<?php require_once "config.php"; $arr_list = array(); if (array_key_exists('aqueduct', $_GET) && array_key_exists('max_result', $_GET)) { $channel = $_GET['channel']; $url = "https://world wide web.googleapis.com/youtube/v3/search?channelId=$channel&guild=engagement&part=snippet&type=video&maxResults=". $_GET['max_result'] ."&key=". GOOGLE_API_KEY; $arr_list = getYTList($url); } ?> This lawmaking includes a configuration file, gets the parameters from the URL, builds an API URL, and then passes it to the helper method we created in the previous step.
In return, you should receive a response containing video information. To display the result add together the below code subsequently your form.
I am not going to focus on the design of a listing. The chief purpose of the tutorial is to present YouTube videos. I'll brandish them in the list format.
<?php if (!empty($arr_list)) { repeat '<ul class="video-listing">'; foreach ($arr_list->items every bit $yt) { echo "<li>". $yt->snippet->title ." (". $yt->id->videoId .")</li>"; } repeat '</ul>'; if (isset($arr_list->nextPageToken)) { echo '<input blazon="hidden" form="nextpagetoken" value="'. $arr_list->nextPageToken .'" />'; repeat '<div id="loadmore">Load More</div>'; } } ?> Here I am looping through the videos and press the video title and video id. If nosotros get the value of nextPageToken we are adding a hidden field and a Load More element. This is because if you accept more than l videos on the channel, you can get the adjacent fix of records using this nextPageToken value. On the click of Load More than, we'll requite an Ajax phone call and fetch the adjacent gear up of videos.
Ajax Call
Write the below JavaScript lawmaking at the end of the alphabetize.php file.
<script> var httpRequest, nextPageToken; document.getElementById("loadmore").addEventListener('click', makeRequest); function makeRequest() { httpRequest = new XMLHttpRequest(); nextPageToken = document.querySelector('.nextpagetoken').value; if (!httpRequest) { alert('Giving up : Cannot create an XMLHTTP instance'); render imitation; } httpRequest.onreadystatechange = function(){ if (this.readyState == 4 && this.status == 200) { var list = JSON.parse(this.responseText); for(var i in list) { if(listing[i].title != undefined && list[i].id != undefined) { var newElement = document.createElement('li'); newElement.innerHTML = '<li>'+ list[i].championship +'('+ listing[i].id +')</li>'; document.querySelector('.video-list').appendChild(newElement); } } if(listing[list.length-1].nextPageToken != undefined) { document.querySelector('.nextpagetoken').value = list[listing.length-1].nextPageToken; } else { var loadmore = document.getElementById("loadmore"); loadmore.parentNode.removeChild(loadmore); } } }; httpRequest.open('Become', 'ajax.php?aqueduct=<?php echo $_GET['channel']; ?>&max_result=<?php echo $_GET['max_result']; ?>&nextPageToken='+nextPageToken, truthful); httpRequest.send(); } </script> For this article, I am using vanilla JavaScript for the ajax call and appending the response to the DOM. To the ajax file I am sending the values of channel id, max_result, and nextPageToken.
The higher up code gives a call to the ajax.php file. This file will give us the side by side set up of records which volition then append to the existing listing.
In the ajax file with the help of given parameters, I'll build the API URL and call the helper method. After receiving the API upshot, I'll create a JSON object containing video information. To the final response, I am also appending a nextPageToken value to become the next prepare of records on subsequent Ajax calls.
ajax.php
<?php require_once "config.php"; $url = "https://www.googleapis.com/youtube/v3/search?channelId=". $_GET['channel'] ."&order=date&part=snippet&blazon=video&maxResults=". $_GET['max_result'] ."&pageToken=". $_GET['nextPageToken'] ."¢ral=". GOOGLE_API_KEY; $arr_list = getYTList($url); $arr_result = array(); if (!empty($arr_list)) { foreach ($arr_list->items as $yt) { array_push($arr_result, ['championship' => $yt->snippet->championship, 'id' => $yt->id->videoId]); } if (isset($arr_list->nextPageToken)) { array_push($arr_result, ['nextPageToken' => $arr_list->nextPageToken]); } } echo json_encode($arr_result); Our JavaScript lawmaking receives this JSON response and appends the result to the existing listing of YouTube videos. This process continues until we detect the value for nextPageToken.
I hope you understand how to get a list of videos on a YouTube aqueduct. For a sake of the tutorial, I am only press the video title and video id. You can print the other data as well depending on your requirement.
Related Articles
- How to Utilize YouTube API to Upload Video On YouTube Channel
- How to Go YouTube Video List past Keywords Using YouTube Search API
- How to Add Google OAuth Login in Website with PHP
If you lot liked this commodity, then please subscribe to our YouTube Channel for video tutorials.
Source: https://artisansweb.net/youtube-api-get-list-youtube-videos/
Post a Comment for "youtube api to upload videos from your website"