Nicoară Talpeș

web and mobile developer

Connect to Youtube API With C#

This blog post will cover how to connect to the Youtube API with C# in .NET .

A use case can be signing users into a website via Youtube. This post will show how to publish a new playlist to the logged in user's channel.

Authorization code

The homepage for the API documentation is here, which points to the .NET sample code page here, which points to more code on github here.

Let's start and use the code on the samples page, which creates a new playlist on the user's channel. We create an ASP MVC 4 project. Just copying the sample code in the project doesn't work since the library functions are not recognized. We proceed by installing from the Package Manager Console:

PM > Install-Package Google.Apis.YouTube.v3

Next, since we have a website, we will use the client-side authentication instructions here.

First we enable the Youtube API for the project from Google API Console site. On this site , we go in Dashboard -> Enable API -> Youtube Data API v3 -> Enable. Then back in Dashboard, choose Create Credentials -> OAuth Client ID -> Web application .

It will save you time later to complete the fields for Javascript Origins with correct values for production - I added http://localhost:55133 and http://nameofmywebsite.com - and for Redirect URI - I added "http://localhost/authorize/" and " http://nameofmywebsite.com/authorize/". This will generate a Client ID and a Client Secret.

With these two , add them to the file client_secrets.json mentioned in the sample code. At this point if you run the project you will get the error "A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll". This is probably because the file client_secrets.json is not correctly specified how to be imported in the code sample, at this line:


UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) // here
        

This problem is described here , with no accepted solution. So let's switch to explicit definition:


public async Task Run()
{
    ClientSecrets secrets = new ClientSecrets() 
    {
        ClientId = " 510267513772-5hq62mr1cs329vprrgp10chps87t4vd3.apps.googleusercontent.com",
        ClientSecret = " test",
    };
    var credentialMethod = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        secrets,
            // This OAuth 2.0 access scope allows for full read/write access to the
            // authenticated user's account.
            new[] { YouTubeService.Scope.Youtube },
            "user",
            CancellationToken.None,
            new FileDataStore(this.GetType().ToString())
        );

             

Make sure the ClientId and ClientSecret don't have a leading space as above (that is carried on at copy from google console), otherwise you will get an OAuth invalid_client error .

And now at run, you will be carried on to a new screen asking for the Youtube account to log-in with. It will then ask a permission, the permission specified by the line of code above YouTubeService.Scope.Youtube. To have successful log-in, we need to add YouTubeService.Scope.YoutubeForceSsl

Asynchronous calling

I have put the above Run method in a class in a folder Infrastructure that is called from the Controller by this line:


public ActionResult Index()
{
    Computation comp = new Computation();
    comp.Run();
             

At this moment the rest of the code quietly doesn't move past

await youtubeService.Playlists.Insert(newPlaylist,"snippet,status").ExecuteAsync();

with a message in the Output that the Thread exited. This is fixed by making the controller method async:

        
public async Task<ActionResult> Index()
{
    Computation comp = new Computation();
    await comp.Run();
                

and now running the code successfully posts a playlist.

This post implemented authorization with OAuth 2.

Further things to explore can be authentication from the front end using the Javascript client library here and reloading the page with the new unlocked content.


Posted on March 7, 2017