ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • React Native | Youtube Video 정보 가져오기
    개발/React Native 2021. 8. 20. 20:04

    React Native에서 react-native-youtube 패키지를 사용하면 Youtube 영상을 앱 내에서 재생하는 것은 가능하지만 재생하는 Video의 제목과 재생시간, 채널명과 같은 기본정보는 가져오지 못한다. Google API 활용하면 Video의 기본정보를 가져올 수 있다. 어딘가 이를 처리해주는 패키지가 있을 것 같은데, 찾을 수가 없어서 필요한 모듈을 직접 만들어 보기로 했다. 

     

    제일 먼저 해야 할 일은 Youtube Data API 이용 권한을 획득하는 것이다.

    방법은 간단하다 아래 주소로 이동하여 프로젝트를 생성하고 API Key를 발급 받으면 된다. 

    https://console.developers.google.com/apis/dashboard

     

    Google Cloud Platform

    하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

    accounts.google.com

     

    1. 프로젝트 생성 & API Key 발급

    우측 상단의 Create Project 선택
    Project Name을 입력한 후 Create 선택
    프로젝트를 생성한 후 API Key 발급을 위해 상단의 'Enable APIs And Services' 선택
    검색창에 'Youtube Data API v3'을 입력하고 검색결과에서 해당 API를 선택함
    Youtube Data API v3 API의 Enable 버튼을 선택하여 API 기능 활성화

     

    API Key 발급을 위해 'Create Credentials > API Key'를 선택함
    API Key가 자동으로 생성되어 팝업 화면에 표시됨. 해당 Key는 잘 보관했다가 나중에 Code에서 이용해야 함.

     

     

    2. Google API를 통한 Youtube 정보 요청

     

    발급받은 API Key를 통해 Youtube영상에 대한 title, channelId, channelTitle, duration을 가져오도록 코드를 작성한다.

    async function _getPlayList(videoId) {
      const YOUTUBE_API_KEY = [위에서 발급한 API Key 입력];
      const url = `https://www.googleapis.com/youtube/v3/videos?id=${videoId}&key=${YOUTUBE_API_KEY}&part=snippet,contentDetails,statistics,status`;
    
      const options = {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json;charset=UTF-8',
        },
      };
      let res = await fetch(url, options);
    
      let resOk = res && res.ok;
      if (resOk) {
        const resData = await res.json();
    
        const {title, channelId, channelTitle} = resData.items[0].snippet;
        const {duration} = resData.items[0].contentDetails;
        return {title, duration, channelTitle, channelId};
      }
    }
    export default _getPlayList;]

    Google API를 통해 Video 정보를 요청하면 아래와 같은 정보를 전달 받을 수 있다. 이 중 Items에 Video와 관련된 정보가 있으며 단일 VideoId를 전달하였음으로 Items[0]를 통해 Video 정보를 확인할 수 있다. 

    {"etag": "65En48KqG9QmRu9IuKp73j50ROw", "items": [{"contentDetails": [Object], "etag": "W1l2DddV5vLcQ70r_r4jte_hyqg", "id": "uCzNn22suak", "kind": "youtube#video", "snippet": [Object], "statistics": [Object], "status": [Object]}], "kind": "youtube#videoListResponse", "pageInfo": {"resultsPerPage": 1, "totalResults": 1}}

    아래는 Items[0]에 보관된 데이터로 기본정보는 snippet 필드에 재생시간과 같은 부가 정보는 contentDetails 필드에서 확인할 수 있다. 

    {"contentDetails": {"caption": "false", "contentRating": {}, "definition": "hd", "dimension": "2d", "duration": "PT1M56S", "licensedContent": true, "projection": "rectangular"}, "etag": "W1l2DddV5vLcQ70r_r4jte_hyqg", "id": "uCzNn22suak", "kind": "youtube#video", "snippet": {"categoryId": "25", "channelId": "UCF4Wxdo3inmxP-Y59wXDsFw", "channelTitle": "MBCNEWS", "defaultAudioLanguage": "ko", "description": "4차 재난지원금 지급이 오늘부터 시작됩니다. 우선, 매출 감소가 확인된 소상공인 270만 명에게 최대 5백만 원씩 지급되고, 대리기사 같은 특수노동자와 프리랜서는 내일부터 지원이 시작됩니다.
    
    
    https://imnews.imbc.com/replay/2021/nw1200/article/6132850_34908.html
    
    
    #소상공인, #특고노동자, #프리랜서", "liveBroadcastContent": "none", "localized": {"description": "4차 재난지원금 지급이 오늘부터 시작됩니다. 우선, 매출 감소가 확인된 소상공인 270만 명에게 최대 5백만 원씩 지급되고, 대리기사 같은 특수노동자와 프리랜서는 내일부터 지원이 시작됩니다.
    
    
    https://imnews.imbc.com/replay/2021/nw1200/article/6132850_34908.html
    
    
    #소상공인, #특고노동자, #프리랜서", "title": "4차 재난지원금 지급 시작…신청 방법은? (2021.03.29/12MBC뉴스)"}, "publishedAt": "2021-03-29T03:30:17Z", "tags": ["MBC", "MBC뉴스", "뉴스데스크", "newsdesk", "뉴스투데이", "newstoday", "8시뉴스", "아침뉴스", "뉴스", "정오뉴스", "news", "코로나19", "추경", "4차 재난지원금", "소상공인", "재난지원금", "특고 노동자", "프리랜서", "신청방법"], "thumbnails": {"default": [Object], "high": [Object], "maxres": [Object], "medium": [Object], "standard": [Object]}, "title": "4차 재난지원금 지급 시작…신청 방법은? (2021.03.29/12MBC뉴스)"}, "statistics": {"commentCount": "200", "dislikeCount": "24", "favoriteCount": "0", "likeCount": "269", "viewCount": "31765"}, "status": {"embeddable": true, "license": "youtube", "madeForKids": false, "privacyStatus": "public", "publicStatsViewable": true, "uploadStatus": "processed"}}
     LOG  {"channelId": "UCF4Wxdo3inmxP-Y59wXDsFw", "channelTitle": "MBCNEWS", "duration": "PT1M56S", "title": "4차 재난지원금 지급 시작…신청 방법은? (2021.03.29/12MBC뉴스)"}

    본 예제에서는 영상의 제목, 채널ID,채널명, 재생시간에 대한 정보를 요청하였으며 아래와 같이 필요한 정보를 잘 가져오는 것으로 확인된다. 

    {"channelId": "UCF4Wxdo3inmxP-Y59wXDsFw", "channelTitle": "MBCNEWS", "duration": "PT1M56S", "title": "4차 재난지원금 지급 시작…신청 방법은? (2021.03.29/12MBC뉴스)"}

     

     

    참고자료

     

    Retrieving Youtube video information from Google APIs using PowerShell

    In this article, I’m using Google APIs to retrieve Youtube public videos data with PowerShell in order to update Microsoft MVP Contributions

    lazywinadmin.com

     

    React Native 앱 제작기 #3 | YouTube Data API 사용법 , 적용하기

    안녕하세요! 바울랩 ‘오현규’ 연구원 입니다. 이번에는 'YouTube Data API'를 사용하는 방법에 대해서 다뤄보도록 하겠습니다! 우선 공식문서를 보겠습니다! 어떤 서비스를 사용하려면 공식 문서

    paullab.tistory.com

     

Designed by Monster Factory