How to Use the YouTube API with Ionic Last update: 2017-09-05

How to Use the YouTube API with Ionic

If you want to use a Google Service like the YouTube REST API you have the chance to make requests even without going through a full user authentication and OAuth process.

For some services you can easily register an API key for your application and make signed requests with that key. And that’s what we will do in this tutorial to receive playlist data and video information directly from Google. Our own little YouTube search app!

Getting a Google API Key for the YouTube API

There are a few steps to get to the key, but all of them are very straight forward so go through these new:

  1. Create a Google account or use your existing
  2. Create a project in the Google Developer console
  3. Inside your new project got to Library and search/select YouTube Data API v3 and hit enable
  4. Go to Credentials and click Create API key

This is now the API key we can use to make requests to the YouTube Data API. In case you want to look up some endpoints or a data format there is a very good documentation about the API here, so if you are looking for all features of the API and things you can do take a closer look at the pages there.

We are now ready to transition to our Ionic app to actually use the API!

Setting up our Ionic YouTube App

We start like always with a blank new Ionic app and add a new provider and page. Make sure to create a module file for that page if your CLI is not doing it. Also, we install the Cordova plugin to get access to the native YouTube player so we can later play our videos directly in that app! Now go ahead and run:

ionic start devdacticYoutube blank
cd devdacticYoutube
ionic g provider yt
ionic g page playlist

ionic cordova plugin add cordova-plugin-youtube-video-player
npm install --save @ionic-native/youtube-video-player

The current CLI will not create any module files for our pages anymore, but as we are using lazy loading here you can easily create a module file for each page following the general scheme for that file. You can find an example here in the listing for home-tabs.module.ts! In order to use the plugin on Android we need to add our YouTube API key from before to our config.xml, so add this entry now:

<preference name="YouTubeDataApiKey" value="[YOUR YOUTUBE API]" />

Finally we need to make sure everything is connected accordingly inside our app.module.ts so change yours to:

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { HttpModule } from '@angular/http';
import { YtProvider } from '../providers/yt/yt';
import { YoutubeVideoPlayer } from '@ionic-native/youtube-video-player';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    YtProvider,
    YoutubeVideoPlayer
  ]
})
export class AppModule {}

Let’s dive into the fun!

Searching for Playlists of a Channel

The first operation our app allows is searching for playlists of a channel. Of course it’s perhaps not a real use case but it’s a good way to demonstrate the functions of the API.

We have created a provider before and we will make all interaction to the API through the provider now. Besides searching for playlists we then also want to get all videos for a playlist so we can drill into a list and display all videos.

Making a request is basically the URL to the according endpoint of the API plus a few parameters, nothing more needed! In our case we need to append the API key, and if you want to specify some other options you can change the response, what will be included or how many items you get back for example.

So our provider is really simple, therefore change your src/providers/yt/yt.ts to:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class YtProvider {
  apiKey = 'YOURKEY';

  constructor(public http: Http) { }

  getPlaylistsForChannel(channel) {
    return this.http.get('https://www.googleapis.com/youtube/v3/playlists?key=' + this.apiKey + '&channelId=' + channel + '&part=snippet,id&maxResults=20')
    .map((res) => {
      return res.json()['items'];
    })
  }

  getListVideos(listId) {
    return this.http.get('https://www.googleapis.com/youtube/v3/playlistItems?key=' + this.apiKey + '&playlistId=' + listId +'&part=snippet,id&maxResults=20')
    .map((res) => {
      return res.json()['items'];
    })
  }
}

That’s all we need for our example, but of course you can try out all the different other endpoints as well.

Now we need to build the logic to make a call to the API, and we will have a simple view with an input field and search button which triggers a call to the API with the current search value. After getting the results back we want to display them, and finally we add another function to open a specific playlist which will push another page and pass the ID of the clicked list so we canload the next data there.

I also added my channel ID so you can directly hit search if you are implementing this to see some results (and don’t forget to subscribe here!).

Now open your src/pages/home/home.ts and change it to:

import { YtProvider } from './../../providers/yt/yt';
import { Component } from '@angular/core';
import { NavController, AlertController} from 'ionic-angular';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  channelId = 'UCZZPgUIorPao48a1tBYSDgg'; // Devdactic Channel ID
  playlists: Observable<any[]>;

  constructor(public navCtrl: NavController, private ytProvider: YtProvider, private alertCtrl: AlertController) { }

  searchPlaylists() {
    this.playlists = this.ytProvider.getPlaylistsForChannel(this.channelId);
    this.playlists.subscribe(data => {
      console.log('playlists: ', data);
    }, err => {
      let alert = this.alertCtrl.create({
        title: 'Error',
        message: 'No Playlists found for that Channel ID',
        buttons: ['OK']
      });
      alert.present();
    })
  }

  openPlaylist(id) {
    this.navCtrl.push('PlaylistPage', {id: id});
  }
}

The view for our first page is also super simple, just an input field and the button plus the list which uses our Observable playlists from the class which holds the playlists of the channel we searched for.

As we have included some information for each playlist we can display a thumbnail, title of that list and even when the list was published. You can also check the console logs to see more information, it’s quite a big response with many details!

Go ahead and finish the first part by changing your src/pages/home/home.html to:

<ion-header>
  <ion-navbar color="danger">
    <ion-title>
      Playlist Search
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-item>
    <ion-label stacked>Channel ID</ion-label>
    <ion-input type="text" [(ngModel)]="channelId"></ion-input>
  </ion-item>
  <button full ion-button (click)="searchPlaylists()" [disabled]="channelId === ''" color="danger">Search Playlists</button>

  <ion-list no-padding>
    <button ion-item *ngFor="let list of playlists | async" (click)="openPlaylist(list.id)">
      <ion-thumbnail item-start>
      <img [src]="list.snippet.thumbnails.standard.url">
    </ion-thumbnail>
    <h2>{{ list.snippet.title }}</h2>
    <p>{{ list.snippet.publishedAt | date:'short' }}</p>
    </button>
  </ion-list>
</ion-content>

You should now already be able to search for data and get a result. If it’s not working by now, perhaps wait a few minute if you just enabled the API as this can take like 10 minutes sometimes!

Loading Videos for a Playlist

The last missing piece of the tutorial is displaying the videos of a selected playlists, but it’s super straight forward after our initial efforts.

We get the ID of the page already passed through the navParams so we only need to make another call through our provider to receive all videos for a specific playlist!

Finally we also add a function to open a specific video by its ID through the Cordova plugin we installed before. I also added a fallback for the browser which will just open the video in a new tab so you can easily test the code without a device.

Go ahead and change your src/pages/playlist/playlist.ts to:

import { YtProvider } from './../../providers/yt/yt';
import { Observable } from 'rxjs/Observable';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform } from 'ionic-angular';
import { YoutubeVideoPlayer } from '@ionic-native/youtube-video-player';

@IonicPage()
@Component({
  selector: 'page-playlist',
  templateUrl: 'playlist.html',
})
export class PlaylistPage {
  videos: Observable<any[]>;

  constructor(private navParams: NavParams, private ytProvider: YtProvider, private youtube: YoutubeVideoPlayer, private plt: Platform) {
    let listId = this.navParams.get('id');
    this.videos = this.ytProvider.getListVideos(listId);
  }

  openVideo(video) {
    if (this.plt.is('cordova')) {
      this.youtube.openVideo(video.snippet.resourceId.videoId);
    } else {
      window.open('https://www.youtube.com/watch?v=' + video.snippet.resourceId.videoId);
    }
  }
}

To display all the videos we use again an ion-list and add a thumbnail and title just like before. The click event will call our function with the id of the video and bring up the native YouTube player or the browser window depending on where you run your app. Finish it up by changing your src/pages/playlist/playlist.html to:

<ion-header>
  <ion-navbar color="danger">
    <ion-title>Playlist</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
    <button ion-item *ngFor="let video of videos | async" (click)="openVideo(video)" detail-none>
      <ion-thumbnail item-start>
      <img [src]="video.snippet.thumbnails.standard.url">
    </ion-thumbnail>
    <h2>{{ video.snippet.title }}</h2>
    <p>{{ video.snippet.description }}</p>
    </button>
  </ion-list>
</ion-content>

Now you are ready to search for playlist of a channel and even display the videos of that playlist with a little thumbnail - directly from YouTube!

Conclusion

You don’t always need a full OAuth flow inside your Ionic app to use Google Services. With an API key you can make requests to some services and enjoy the full power of the available Google data to spice up your apps!

You can also find a video version of this article below.

Happy Coding, Simon

https://youtu.be/rPVvwj8uGnk