Results 1 to 1 of 1

Thread: Youtube Data API v3 - issues with credentials

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jul 2013
    Posts
    108

    Youtube Data API v3 - issues with credentials

    I am trying for the first time to use the Youtube Data API v3, precisely the Playlists: insert method that operates in the user's private data, to add a certain video to my personal playlist. To work with user's private data, I need OAuth permissions and I need User Permissions that include at least one of these scopes
    Name:  42fYi.png
Views: 590
Size:  26.9 KB
    The OAuth file called secret.json is saved into the debug folder of the project.


    The API keys work instead for public data, which I have already used to derive the ID of the first search result starting from a qwery (I will also insert this code to show the differences). Online, I found GitHub samples in c # which I converted to vb.net and modified the obsolete code such as

    Code:
     GoogleClientSecrets.Load(stream).Secrets
    to
    Code:
    GoogleClientSecrets.fromstream(stream).Secrets
    So the final code is

    Code:
    Imports System
    Imports System.Collections.Generic
    Imports System.IO
    Imports System.Net
    Imports System.Reflection
    Imports System.Text
    Imports System.Threading
    Imports System.Threading.Tasks
    Imports Google.Apis.Auth.OAuth2
    Imports Google.Apis.Services
    Imports Google.Apis.Upload
    Imports Google.Apis.Util.Store
    Imports Google.Apis.YouTube.v3
    Imports Google.Apis.YouTube.v3.Data
    Public Class Form1
    
        Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Try
                Await RetrieveID()
            Catch ex As AggregateException
    
                For Each inner In ex.InnerExceptions
                    MsgBox("Error: " & inner.Message)
                Next
            End Try
        End Sub
        Private Async Function RetrieveID() As Task
            Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
                .ApiKey = "my api key",
                .ApplicationName = Me.[GetType]().ToString()
            })
            Dim credential As UserCredential
    
            Using stream = New FileStream("secret.json", FileMode.Open, FileAccess.Read)
               credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromStream(stream).Secrets, {YouTubeService.Scope.Youtube}, "user", CancellationToken.None, New FileDataStore(Me.[GetType]().ToString()))
            End Using
    
            Dim searchListRequest = youtubeService.Search.List("snippet")
            searchListRequest.Q = TextBox1.Text
            searchListRequest.MaxResults = 1
            Dim searchListResponse = Await searchListRequest.ExecuteAsync()
            Dim videos As List(Of String) = New List(Of String)()
            Dim channels As List(Of String) = New List(Of String)()
            Dim playlists As List(Of String) = New List(Of String)()
    
            For Each searchResult In searchListResponse.Items
    
                videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId))
    
            Next
    
            MsgBox(String.Format("Videos:" & vbLf & "{0}" & vbLf, String.Join(vbLf, videos)))
    
        End Function
    
        Private Async Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    
            Try
                Await PlaylistUpdates()
            Catch ex As AggregateException
    
                For Each inner In ex.InnerExceptions
                    MsgBox("Error: " & inner.Message)
                Next
            End Try
        End Sub
    
        Private Async Function PlaylistUpdates() As Task
    
            Dim credential As UserCredential
    
    
    
            Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
                .HttpClientInitializer = credential,
                .ApplicationName = Me.[GetType]().ToString()
            })
            Using stream = New FileStream("secret.json", FileMode.Open, FileAccess.Read)
                credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromStream(stream).Secrets, {YouTubeService.Scope.Youtube}, "user", CancellationToken.None, New FileDataStore(Me.[GetType]().ToString()))
            End Using
            Dim newPlaylistItem = New PlaylistItem()
            newPlaylistItem.Snippet = New PlaylistItemSnippet()
            newPlaylistItem.Snippet.PlaylistId = "PL4_Dx88dpu7cEY_cBjTZFFM1tVKF5Plsx"
            newPlaylistItem.Snippet.ResourceId = New ResourceId()
            newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video"
            newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI"
            newPlaylistItem = Await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync()
            Console.WriteLine("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, "PL4_Dx88dpu7cEY_cBjTZFFM1tVKF5Plsx")
        End Function
    End Class
    But despite that, I get the error

    " The service YouTube as thrown an exception. HttpStatusCode is Unauthorize. APi keys are not supported by this API. Expected OAuth 2 access token or other authentication credentials that assert a principal".
    as soon as I click button 2 on the line
    Code:
    Await PlaylistUpdates()
    I tried to change Me. [GetType] (). ToString () to the application name used in Google console but it didn't fix the problem. However, I noticed a warning

    Name:  U9uMSh2.jpg
Views: 500
Size:  32.8 KB

    p.s. (it doesn't matter if you see the api key, it's test on a test account). So I went back to the github sample and tried to follow the order of the code to avoid that warning, so the code of the PlaylistUpdates function becomes


    Code:
    Private Async Function PlaylistUpdates() As Task
    
           Dim credential As UserCredential
    
           Using stream = New FileStream("secret.json", FileMode.Open, FileAccess.Read)
               credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.fromstream(stream).Secrets, {youtubeService.Scope.Youtube}, "user", CancellationToken.None, New FileDataStore(Me.[GetType]().ToString()))
           End Using
    
           Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
           .HttpClientInitializer = credential,
           .ApplicationName = Me.[GetType]().ToString()
       })
           Dim newPlaylistItem = New PlaylistItem()
           newPlaylistItem.Snippet = New PlaylistItemSnippet()
           newPlaylistItem.Snippet.PlaylistId = "PL4_Dx88dpu7cEY_cBjTZFFM1tVKF5Plsx"
           newPlaylistItem.Snippet.ResourceId = New ResourceId()
           newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video"
           newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI"
           newPlaylistItem = Await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync()
           Console.WriteLine("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, "PL4_Dx88dpu7cEY_cBjTZFFM1tVKF5Plsx")
       End Function
    but now it shows the error

    Local variable 'youtubeService' cannot be referred to before it is declared.

    on the line

    Code:
    credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.fromstream(stream).Secrets, {youtubeService.Scope.Youtube}, "user", CancellationToken.None, New FileDataStore(Me.[GetType]().ToString()))
    I don't really know how to bother .. I am sure I have activated all the necessary api, scopes and permissions, as well as I have successfully downloaded the json file for the AOuth and put it in the debug folder .. I don't understand how to hit my head anymore. Some idea? Thank you
    Last edited by matty95srk; Aug 31st, 2022 at 09:52 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width