Home > Enterprise >  using youtube API with Google Apps Scripts
using youtube API with Google Apps Scripts

Time:11-01

I am not able to test my scripts. If you can help with the code here - it is not working As per documentation - https://developers.google.com/youtube/v3/docs/videos/insert

  if (serviceYT.hasAccess()) {
  url = 'https://youtube.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&mine=true&key='  API_KEY;
  var data;
  data = '{"snippet":{"title":"testtitle","description":"testdes","categoryId":"19","tags":["asdf","sadfds"]},"status":{"privacyStatus":"public"}}';

  var options =  {
    'headers': {
      'Authorization': 'Bearer '   serviceYT.getAccessToken()
      ,'Accept': 'application/json'
    },
    'contentType': 'application/json',
    'method' : 'POST',
    'payload' : data,
    'muteHttpExceptions' : true
  };
  
  //execute and handle the response
  var response = UrlFetchApp.fetch(url, options);
  var responseCode = response.getResponseCode();
  var result = JSON.parse(response.getContentText());
  Logger.log(result);

}

My questions -

  1. where to put the video?
  2. Resolution of the error I am getting:

{error={message='status', code=400.0, errors=[{reason=unexpectedPart, domain=youtube.part, message='status', location=part, locationType=parameter}]}}

A youtube object (a empty video basically) is successfully added to the youtube which is visible via studio. its a empty video but the title, description, status etc... other things are correcty setup.

Any ideas on how to add the media or video?? Where in the payload the video blob has to be added?

I am not able to get it in the documentation. https://developers.google.com/youtube/v3/docs/videos/insert

CodePudding user response:

I believe your goal is as follows.

  • You want to upload a movie file to your YouTube channel with the title, description, and so on.
  • The movie file is put in your Google Drive.
  • You want to achieve this by directly requesting to the endpoint using UrlFetchApp.

In this case, how about the following modified script?

Modified script:

Before you use this script, please enable YouTube Data API v3 and add the scope of https://www.googleapis.com/auth/youtube. And please set the file ID of the movie file in your Google Drive to const fileId = "###";.

serviceYT.getAccessToken() is from your script.

function myFunction() {
  const fileId = "###"; // Please set the file ID of movie file on the Google Drive.
  const metadata = {
    "snippet": { "title": "testtitle", "description": "testdes", "categoryId": "19", "tags": ["asdf", "sadfds"] },
    "status": { "privacyStatus": "public" }
  };

  const url = 'https://www.googleapis.com/upload/youtube/v3/videos?part=snippet,status';
  const file = DriveApp.getFileById(fileId);
  const boundary = "xxxxxxxxxx";
  let data = "--"   boundary   "\r\n";
  data  = "Content-Type: application/json; charset=UTF-8\r\n\r\n";
  data  = JSON.stringify(metadata)   "\r\n";
  data  = "--"   boundary   "\r\n";
  data  = "Content-Type: "   file.getMimeType()   "\r\n\r\n";
  const payload = Utilities.newBlob(data).getBytes().concat(file.getBlob().getBytes()).concat(Utilities.newBlob("\r\n--"   boundary   "--").getBytes());
  const options = {
    method: "post",
    contentType: "multipart/form-data; boundary="   boundary,
    payload: payload,
    headers: { 'Authorization': 'Bearer '   serviceYT.getAccessToken() },
    muteHttpExceptions: true,
  };
  const res = UrlFetchApp.fetch(url, options).getContentText();
  console.log(res);
}
  • In your script, you are using the endpoint of url = 'https://youtube.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&mine=true&key=' API_KEY;. Your data has the properties of snippet and status. In this case, it is required to use the endpoint of https://www.googleapis.com/upload/youtube/v3/videos?part=snippet,status.

  • In order to upload the movie file, it is required to request with multipart/form-data.

  • When this script is run, the movie file on Google Drive is uploaded to YouTube.

Note:

  • In the current stage, even when "privacyStatus": "public" is used, the uploaded video is not public. About this, you can see it at the official document as follows. Ref

    All videos uploaded via the videos.insert endpoint from unverified API projects created after 28 July 2020 will be restricted to private viewing mode. To lift this restriction, each API project must undergo an audit to verify compliance with the Terms of Service. Please see the API Revision History for more details.

  • When you use the YouTube API at Advanced Google services, you can use the following simple script. Ref

      function myFunction2() {
        const fileId = "###"; // Please set the file ID of movie file on the Google Drive.
        const res = YouTube.Videos.insert({
          "snippet": { "title": "testtitle", "description": "testdes", "categoryId": "19", "tags": ["asdf", "sadfds"] },
          "status": { "privacyStatus": "public" }
        }, ["snippet", "status"], DriveApp.getFileById(fileId).getBlob());
        console.log(res);
      }
    

References:

  • Related