← Other topics

YouTube API & PHP - Edit video details (google-api-php-client)

Video Notes

Click here to go directly to the code...

Guides in this series:

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

  1. Authorize Client access token
  2. Query for the video’s existing details
  3. Create a new Google\Service\YouTube\Video instance which is used perform the edit
  4. 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);

If this info helped you out you can say thanks and support future content by clicking my Amazon affiliate link: https://amzn.to/3UtgnYk. If you make a purchase on Amazon within 24 hours of clicking the link I may receive a micro-commission and it costs you nothing extra. Any income from these sales goes directly to supporting me in making new videos and guides. Thank you for your support!

← Other topics