Code Monkey home page Code Monkey logo

youtube-api-v3-search's Introduction

youtube-api-v3-search

Build Status

YouTube Search Google API for Node.js and Browser

Search for YouTube videos, channels, playlists and live events via Google API

  • Node.js using https and in the Browser using XMLHttpRequests

  • Super light no third-party libraries Added browser-resolve for performance.

  • Supports the Prmise API

  • Thanks to @MaximVanhove for adding Support for CommonJS, AMD and global variable.


Installing

==========

Using npm:

 npm install youtube-api-v3-search

Using cdn:

 <script src="https://unpkg.com/[email protected]/dist/youtube-api-v3-search.min.js"></script>

Example Usage

=============

const searchYoutube = require('youtube-api-v3-search');

or

import searchYoutube from 'youtube-api-v3-search';

Callbacks

/**
 * Searching YouTube.
 * @param {string} $YOUTUBE_KEY youtube api-key
 * @param {Object} $options search parameters.
 * @param {function} callback( @param error , @param result).  
 * @return {void}
 */

searchYoutube($YOUTUBE_KEY,$options,callback);

Promises Just don't callback and you'll get a Promise :)

// NOT passing callback as the 3rd argument it returns Promise
/**
 * Searching YouTube.
 * @param {string} $YOUTUBE_KEY youtube api-key
 * @param {Object} $options search parameters.
 * @return {Promise} The result of the search .
 */

searchYoutube($YOUTUBE_KEY,$options);

Async/Await

async () => {
  let result = await searchYoutube($YOUTUBE_KEY,options);
}

Options

[options/parameters]

Search Options

The q parameter specifies the query term to search for.

The part parameter specifies a comma-separated list of one or more search resource properties that the API response will include. Set the parameter value to snippet.

The type parameter restricts a search query to only retrieve a particular type of resource. The value is a comma-separated list of resource types. The default value is video,channel,playlist.

Acceptable values are:

  • channel
  • playlist
  • video

Example

const options = {
  q:'nodejs',
  part:'snippet',
  type:'video'
}

youtube-api-v3-search's People

Contributors

lionroar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

youtube-api-v3-search's Issues

XMLHttpRequest is not defined when running under node

While running the latest version on node the follow error occurs:

ReferenceError: XMLHttpRequest is not defined
    at e.exports (.../node_modules/youtube-api-v3-search/dist/youtube-api-v3-search.min.js:1:940)
    at e.exports (.../node_modules/youtube-api-v3-search/dist/youtube-api-v3-search.min.js:1:1560)
    at e.exports (.../node_modules/youtube-api-v3-search/dist/youtube-api-v3-search.min.js:1:870)

It would appear that the browser version is trying to be used instead of the node version.
The issue doesn't occur on version 1.1.0, but I am not sure which version brakes it

Latest version broke on react-native apps

Hey there I was on version 1.1.3 and it was working super smooth. Recently after upgrading to the latest version, the functionality of my app has broken so I had to revert back to v1.1.3. Please consider using pure JS component in this project. Here are error logs attached below. Btw this project is awesome.

Failed building JavaScript bundle.
[18:57:00] The package at "node_modules/youtube-api-v3-search/src/request/node-request.js" attempted to import the Node standard library module "https". It failed because React Native does not include the Node standard library.

Get error

i provide my youtube_key and get error

errors: [ { domain: 'usageLimits', reason: 'keyInvalid', message: 'Bad Request' } ], code: 400, message: 'Bad Request'

Allow to send etag header

req.setRequestHeader('If-None-Match', etag);

https://stackoverflow.com/questions/48359272/how-to-use-etag-with-the-youtube-api

I did something like this quickly:

https://github.com/LionRoar/youtube-api-v3-search/blob/master/dist/youtube-api-v3-search.js

@@ -103,26 +103,16 @@
       /***/ function (module, exports, __webpack_require__) {
         'use strict';

+        module.exports = function (url, etag) {
+          const req = new XMLHttpRequest();
-        module.exports = function (url) {
-          var req = new XMLHttpRequest();
           return new Promise(function (resolve, reject) {
+            req.onreadystatechange = () => {
+              if (req.readyState === XMLHttpRequest.DONE) {
+                if (req.status === 0 || (req.status >= 200 && req.status < 400)) {
+                  if (req.status === 304) {
+                    resolve({ status: req.status, data: null });
+                    return;
+                  }
+                  // The request has been completed successfully
+                  try {
+                    const response = JSON.parse(req.responseText);
+                    resolve(response);
+                  } catch (error) {
+                    console.log('cannot parse', req.responseText);
+                    resolve(req.responseText);
+                  }
-            req.onreadystatechange = function () {
-              if (this.readyState == 4) {
-                if (this.status == 200) {
-                  var response = JSON.parse(this.response);
-                  resolve(response);
                 } else {
+                  const err = JSON.parse(req.responseText);
-                  var err = JSON.parse(this.response);
                   reject(err);
                 }
               }
@@ -131,11 +121,6 @@
               reject(new Error(this.statusText));
             };
             req.open('GET', url, true);
+            if (etag) {
+              req.setRequestHeader('If-None-Match', etag);
+            }
-
             req.send(null);
           });
         };
@@ -153,18 +138,16 @@
           if (!key && typeof cb === 'function') return cb(new Error('API Key is required'));
           else if (!key) throw new Error('API Key is required');
           fillData(key, options);
           var q = querystring.stringify(config.options);
           if (typeof cb === 'function')
+            request(config.URL + q, config.options.etag)
-            request(config.URL + q)
               .then(function (res) {
                 return cb(null, res);
               })
               .catch(function (err) {
                 return cb(err);
               });
+          else return request(config.URL + q, config.options.etag);
-          else return request(config.URL + q);

Getting Error: socket hang up and it does not pass as error

More often than not, I get this error:
`Error: socket hang up
^

SyntaxError: Unexpected token E in JSON at position 0
at JSON.parse ()
at ClientRequest.https.get.on (/home/user/project/node_modules/youtube-api-v3-search/src/request/node-request.js:15:22)
at emitOne (events.js:116:13)
at ClientRequest.emit (events.js:211:7)
at TLSSocket.socketErrorListener (_http_client.js:387:9)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)It locks up the entire program until I close it. Is there any reason for this? Am I missing something? Any help would be appreciated. The options I'm passing: let options = {
q:search,
part:'snippet',
type:'video',
maxResults:5
}`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.