How To Integrate YouTube API Using LWC In Salesforce?

How To Integrate YouTube API Using LWC In Salesforce?

In this blog, you will learn how you can integrate YouTube API using lightning web component.


Follow Below Steps for YouTube API Integration

1) Login to https://console.developers.google.com to create YouTube API Key.

2) Click on the dropdown next to the Google Cloud Logo to create a new project.


3) Create a new YouTube integration Project.


 4) Enter Project Name and click on create button.


5) Once the project is created, you will receive a notification.

6) Click on Select Project from the notification.


7) Click on Library from the slide bar.


8)  Search for YouTube Data API and select it.


 9) Click on Enable Button


10) Click on Credentials, then click on create credentials and select API Key.


11)  API will be created, copy and save it in notepad. we need this to use it in our component.



IMPORTANT :

  • To add this go to Setup
  • Remote Site Settings and 
  • Update your API Key LWC.Js file 


Source Code

LWC.html

<template>

    <lightning-card >

        <img src="https://upload.wikimedia.org/wikipedia/commons/0/09/YouTube_full-color_icon_%282017%29.svg" width="45" height="auto" style="margin: 0px 5px 5px 10px;"><b>  YouTube</b>

            <div class="slds-grid">

                    <lightning-input type="text" style="margin-top: -55px;margin-left: 150px;width: 25em;" value={searchInput} onchange={handleSearch}></lightning-input>

                    <lightning-button variant="brand" label="Search" onclick={handleSubmit} style="margin-top: -36px;margin-left: 5px;"></lightning-button>

            </div>

  

          <template for:each={finalresult} for:item="acc">

               <div key={acc.Id}>

                    {acc.Name}

               </div>

          </template>

    <div class="slds-grid slds-gutters">

        <div class="slds-col slds-size_2-of-3">

    <article class="slds-card" style="margin: 5px;">

        <div class="slds-card__body slds-card__body_inner" style="padding: 0px;margin: 3px;">

            <iframe style="height:400px;width:100%;border-radius: 2px;" allowfullscreen src={viewUrl}></iframe>

        </div>

    </article>

    </div>

    <div class="slds-border_left">

    <div style="height: 400px; width:auto" class="slds-scrollable_y slds-col slds-size_1-of-3">

       

        <template for:each={videoResults} for:item="item">

        <div class="" key={item.id}>

                <div class="slds-box  slds-grid">

                    <header class="slds-media slds-media_center slds-has-flexi-truncate">

                        <div class="slds-media__figure">

                            <img style="width: 150px;height: 100px;border-radius: 9px;" src={item.thumbnails}/>

                        </div>

                        <div class="slds-media__body">

                            <h2 class="slds-card__header-title">

                                <a onclick={watchVideo} class="slds-card__header-link" data-id={item.videoId}>

                                    <span>{item.title}</span>

                                </a>

                            </h2>

                            <br/>

                            <span style="font-weight: bold;">By: {item.channelTitle}</span>

                        </div>

                    </header>

                </div>

       </div>

        </template>

    </div>

    </div>

    </div>

</lightning-card>

</template>



LWC.js


import { LightningElement,track } from 'lwc';

import getVideos from '@salesforce/apex/YoutubeController.getYoutubeVideos';


export default class Youtube extends LightningElement {


    API_KEY= 'PASTE_API_KEY_HERE';

    END_POINT= 'https://www.googleapis.com/youtube/v3/search';


    @track finalresult = [];

    @track finalError = '';

    @track searchInput = 'salesforce';

    @track videoResults = [];

    @track viewUrl = '';


    connectedCallback(){

         this.handleSubmit();

    }


    handleSearch(event){

         this.searchInput = event.target.value;

    }


    handleSubmit(){

  getVideos({SEARCH_KEY:this.searchInput,SEARCH_URL:this.END_POINT,API_KEY:this.API_KEY})

         .then ((results)=>{

              this.videoResults = results;

              if (this.videoResults.length > 0) {

                   this.showVideoInIframe(this.videoResults[0].videoId);

              }

         })

         .catch((error)=>{

              this.finalError = error.body.message;

              console.log('This is final video results ::'+ this.finalError);

         })

    }


    showVideoInIframe(videoId){

         this.viewUrl = 'https://www.youtube.com/embed/'+videoId;

     }


    watchVideo(event){

         let slt = event.currentTarget.dataset.id;

         this.viewUrl = 'https://www.youtube.com/embed/'+slt;

    }

}


LWC.xml


<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>55.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__AppPage</target>

        <target>lightning__HomePage</target>

        <target>lightning__Tab</target>

    </targets>

</LightningComponentBundle>


Apex Classes

YoutubeController

public with sharing class YoutubeController {

    @AuraEnabled(cacheable=true)

        public static list<mywrapper> getYoutubeVideos(string SEARCH_KEY, string SEARCH_URL, string API_KEY){

            SEARCH_KEY = SEARCH_KEY == null ? 'salesforce' : SEARCH_KEY;

            Http http = new Http();

            HttpRequest req = new HttpRequest();

            Httpresponse res = null;

            String endpoint  = SEARCH_URL +

            '?part=snippet' +

            '&maxResults=20' +

            '&type=video' +

            '&q=' + EncodingUtil.urlEncode(SEARCH_KEY, 'UTF-8') +

            '&key=' + API_KEY;

            req.setEndPoint(endpoint);

            req.setMethod('GET');

            res = http.send(req);

            YoutubeResponseController.Response response = (YoutubeResponseController.Response)JSON.deserialize(res.getBody(), YoutubeResponseController.Response.class);

            List<YoutubeResponseController.Item> items  =  response.items;

            List<mywrapper> wrp  = new List<mywrapper>();

            for (YoutubeResponseController.Item itemObj : items) {

                mywrapper YTWrap = new mywrapper();

                YTWrap.videoId = itemObj.id.videoId;

                YTWrap.description = itemObj.Snippet.description;

                YTWrap.thumbnails = itemObj.Snippet.thumbnails.medium.url;

                YTWrap.title = itemObj.Snippet.title;

                YTWrap.channelTitle = itemObj.Snippet.channelTitle;

                wrp.add(YTWrap);

            }

            return wrp;

        }


        public class mywrapper{

            @AuraEnabled public string videoId {get;set;}

            @AuraEnabled public string description {get;set;}

            @AuraEnabled public String thumbnails {get;set;}

            @AuraEnabled public String title {get;set;}

            @AuraEnabled public String channelTitle {get;set;}

            @AuraEnabled public String publishedAt  {get;set;}

        }

}


YoutubeResponseController

public with sharing class YoutubeResponseController {
    public List<YoutubeResponseController.Item> items { get; set; }    
    public class Response {
        public String kind { get; set; }
        public String etag { get; set; }
        public String nextPageToken { get; set; }
        public String prevPageToken { get; set; }
        public YoutubeResponseController.PageInfo pageInfo { get; set; }
        public List<YoutubeResponseController.Item> items { get; set; }
    }
    
    public class PageInfo {
        public Integer totalResults { get; set; }
        public Integer resultsPerPage { get; set; }
    }
    
    public class Item {
        public String kind { get; set; }
        public String etag { get; set; }
        public YoutubeResponseController.Id id { get; set; }
        public YoutubeResponseController.Snippet snippet { get; set; }
    }
    
    public class Id {
        public String kind { get; set; }
        public String videoId { get; set; }
    }
    
    public class Snippet {
        public Datetime publishedAt { get; set; }
        public String channelId { get; set; }
        public String title { get; set; }
        public String description { get; set; }
        public YoutubeResponseController.Thumbnails thumbnails { get; set; }
        public String channelTitle { get; set; }
        public String liveBroadcastContent { get; set; }
    }
    
    public class Thumbnails {
        public YoutubeResponseController.Thumbnail medium { get; set; }
        public YoutubeResponseController.Thumbnail high { get; set; }
    }
    
    public class Thumbnail {
        public String url { get; set; }
    }
}


Demo


Follow Us

Posted By : Sudeer Kamat Date :

view_module Related

  • How to Create Netflix Card Animation Effect In LWC?How to Create Netflix Card Animation Effect In LWC?
  • How To Integrate Github Using Fetch API In LWC?How To Integrate Github Using Fetch API In LWC?
  • How To Create Animate Email Notification Using LWC?How To Create Animate Email Notification Using LWC?
  • How to Create Apple Music Card Animation Effect In LWC?How to Create Apple Music Card Animation Effect In LWC?
  • How to Create Owl Animated Login Screen In LWC?How to Create Owl Animated Login Screen In LWC?

Comments 0