Web

[Youtube API] 검색어 입력으로 썸네일 이미지 받아오기

dearbeany 2022. 8. 30. 14:21

Youtube API 서버로부터 데이터를 받는다. 해당 서버의 주소는 아래와 같다.

-> 해당 API를 쓰기위한 필수/옵션 사항을 안내한다.

 

https://developers.google.com/youtube/v3/docs/search/list

 

Search: list  |  YouTube Data API  |  Google Developers

Search: list API 요청에 지정된 쿼리 매개변수와 일치하는 검색결과의 모음을 반환합니다. 기본적으로 검색결과의 집합은 쿼리 매개변수와 일치하는 video, channel, playlist 리소스를 식별하지만, 특정

developers.google.com

 

 

params

- axios에 API_KEY를 params의 key-value으로 전달해주지 않는다면, 403 forbidden 에러 발생. 즉, 권한이 존재하지 않는다.

- 키는 아래에서 발급받도록 한다. API 및 서비스 > 사용자 인증 정보

https://console.cloud.google.com/apis/credentials?project=ace-mission-361004&supportedpurview=project 

 

Google 클라우드 플랫폼

로그인 Google 클라우드 플랫폼으로 이동

accounts.google.com

- (필수 매개변수)part : 'snippet' 필수매개변수이기에 반드시 지정해주어야 함.

- q : value로 받는 검색어 키워드들을 전달해준다. (없다면 검색어 ssafy에 해당하는 데이터를 받아올 수 없다.)

- type : video로만 제한한다. 

 

 

.then => 체이닝

비동기 통신인데 동기적으로 하게끔 만든다. res.data.items 응답받은 데이터의 items 배열만을 리턴한다.

res의 배열이 가진 for-each문/for문을 사용해 순회할 수도 있다.

<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
  <title>Youtube 검색</title>
</head>

<body>
  <h1>Youtube 검색</h1>
  <input type="text" id="search" placeholder="검색어를 입력해주세요.">
  <button id="search-btn">검색</button>
  <hr>
  <h2>검색 결과</h2>
  <iframe width="560" height="315" src="https://www.youtube.com/embed/CgKUIHw2lHc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
  <ul id="list">

  </ul>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    const URL = "https://www.googleapis.com/youtube/v3/search"
    const API_KEY = "AIzaSyCBJPhXDE6AbuhAoH-Z2JbHSRSVvTP-G50"
    



    const btn = document.querySelector("#search-btn")

    btn.addEventListener("click", () => {
      const value = document.querySelector("#search").value

      axios({
        url: URL,
        method: 'GET',
        params: {
          key: API_KEY,
          part: 'snippet',
          q: value,
          type: 'video',
          maxResults: 20,
        }
      })
        .then((res) => {
          return res.data.items
        })
        .then((res) => {
          const ulTag = document.querySelector("#list")

          for(let i = 0; i< res.length; i++){
            let liTag = document.createElement("li")
            let imgTag = document.createElement("img")

            imgTag.src = res[i].snippet.thumbnails.default.url
            liTag.appendChild(imgTag)
            ulTag.appendChild(liTag)
          }

          //아래와 같이 순회할 수도 있다.
          // res.forEach(element => {
          //   console.log(element)
          // });
        })
        .catch((err) => {
          console.log(err)
        })


    })
  </script>
</body>

</html>

 

<실행 결과>

1. 키워드 입력 후 검색 버튼을 클릭하면

2. 검색결과 밑으로 20개의 썸네일 이미지가 리스트로 제공된다.

 

 

 

Youtube 검색

Youtube 검색


검색 결과