Click here to go directly to the code...
Guides in this series:
- Part 1: Initial setup
- Part 2: Get video details
- Part 3: Get all videos from a channel
- Part 4: OAuth Connection
- Part 5: Edit video details
Intro
In the last part of this series, Part 4 OAuth Connection, we saw how to set up an OAuth Connection with the YouTube API using PHP and the google-api-php-client package.
Building on this, this video covers an example of editing a video’s details using that OAuth connection.
Summary
- Authorize Client access token
- Query for the video’s existing details
- Create a new
Google\Service\YouTube\Video
instance which is used perform the edit - Create a new
Google\Service\YouTube\VideoSnippet
instance which is used to define the snippet details we will edit
Note that when updating a video’s snippet (as we are doing in this example), it’s required that you provide the title
and categoryId
(ref) as part of this update. It’s for this reason that before we do the update, we query for the video’s existing details which includes its categoryId
. This information is then used as part of the update.
The code
<?php
# ref: # https://developers.google.com/youtube/v3/docs/videos/update
session_start();
require_once 'vendor/autoload.php';
use Google\Client;
use Google\Service\YouTube;
# Edit details
$videoId = '2hDQp6M42hg'; # Must be a video that belongs to the currently auth’d user
$newTitle = 'New Laravel application with Herd and DBngin...';
# Set up client and service
$client = new Client();
$service = new YouTube($client);
# Authorize client
# This assumes the auth process has already happened via the code
# available here: https://codewithsusan.com/notes/youtube-api-php-oauth-connection#the-code
if (!empty($_SESSION['google_oauth_token'])) {
$client->setAccessToken($_SESSION['google_oauth_token']);
} else {
# If not authorized, redirect back to index
header('Location: index.php');
}
# Get the existing snippet details for this video pre-edit
$response = $service->videos->listVideos(
'snippet',
['id' => $videoId]
);
$video = $response[0];
$snippet = $video->snippet;
# Output the snippet details before the edits
dump($snippet);
# Set the edits
$snippet->setTitle($newTitle);
# Set the snippet
$video->setSnippet($snippet);
# Do the update
$response = $service->videos->update('snippet', $video);
dump($response->snippet);