본문 바로가기
Programming/HTML & CSS & JavaScript

Google Api -Youtube data Api v3

by yoon9i 2023. 12. 26.

api 를 통해서 youtube 영상 띄우기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YouTube API Example</title>
    <style>
        .video-container {
            width: 640px;
            height: 360px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div id="videos-container"></div>

    <script>
        // Replace 'YOUR_API_KEY' with the API key you obtained from Google Cloud Console
        const apiKey = 'YOUR_API_KEY';

        // Replace 'CHANNEL_ID' with the YouTube channel ID you want to get videos from
        const channelId = 'CHANNEL_ID';

        // Load YouTube API script
        const script = document.createElement('script');
        script.src = 'https://apis.google.com/js/api.js';
        document.head.appendChild(script);

        script.onload = () => {
            gapi.load('client', () => {
                gapi.client.init({
                    apiKey: apiKey,
                    discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest'],
                }).then(() => {
                    return gapi.client.youtube.search.list({
                        part: 'snippet',
                        channelId: channelId,
                        type: 'video',
                        order: 'viewCount',
                        maxResults: 3,
                    });
                }).then(response => {
                    const videosContainer = document.getElementById('videos-container');
                    response.result.items.forEach(video => {
                        const videoContainer = document.createElement('div');
                        videoContainer.className = 'video-container';
                        videoContainer.innerHTML = `
                            <iframe width="100%" height="100%" src="https://www.youtube.com/embed/${video.id.videoId}" frameborder="0" allowfullscreen></iframe>
                            <h2>${video.snippet.title}</h2>
                            <p>${video.snippet.description}</p>
                        `;
                        videosContainer.appendChild(videoContainer);
                    });
                }).catch(error => {
                    console.error('Error loading YouTube API', error);
                });
            });
        };
    </script>
</body>
</html>