Using the YouTube API

My group decided to utilize the YouTube API for a project, thus forcing me to learn how to use external APIs in two days to deploy a karaoke app. Here are sweet way to get set up with a simple search request using the Google JS library.

Get Your API Key

Actually, just get your API key from the Google Developers Console. For the purposes of creating a simple app that displays or shows videos, browser keys are perfect. If you want your users to be able to personalize their content, use OAuth instead

Secure that Key

Never, ever, ever, ever, ever place your API key in your file. Hackers can easily grab it and use it for unauthorized purposes which would make Google very upset. Instead, store it in JSON file and use an AJAX call to get the object

Serve the static file in your server like this.

The express.static(‘api’) is what allows static files to be served in your Express server.

In my api folder, I have a cofig.JSON file that has the API key stored in an object.

Using AJAX to serve access the object

Accessing the JSON object with an AJAX call
Accessing the JSON object with an AJAX call

The url points to the file and it is assigned to variable named key.

Add the folder to your .gitignore file and write a place holder that points to the file like this

.gitignore will not commit my API Key to Github
.gitignore will not commit my API Key to Github

Google has a really useful article on Securing your API Key. Take a look!

For development purposes, make sure you set the HTTP referrer to be localhost:// so that you can make HTTP requests to the server.

Import the Libraries in your HTML File

The first script import statement allows the API to load while the second allows for requests.

Import Google APIs

Set The Key

Though in beta, Google has released  JS library to use with the YouTube API. How cool is that?

The key first needs to be established using the native method

gapi.client.setApiKey({/*REFERENCE TO YOUR API KEY GOES HERE*/})

Load The YouTube API and Make A Request

The method gapi.client.load will load the API and deliver a promise

Async call to Youtubegapi.client.request({path, params }) is what sends the request. Params is where you identify what video(s) you are searching for. Google has a great console that shows you what the GET request looks like and what JSON object is returned. Check it out here

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s