1. https://console.cloud.google.com/apis
위 사이트 로그인 후
My Project 생성하여, YouTube Analytics API, YouTube Data API v3 사용처리
API 및 서비스 > API 및 서비스 사용 설정 > YouTube에 API 선택하여 클릭 > API 사용해보기 클릭 > 사용 설정된 API 및 서비스에 추가됨 확인
2. YouTube Data API v3 KEY 발급
사용자 인증 정보 > 사용자 인증 정보 만들기 > API 키 발급
API 키 발급내역 확인
3. 재생목록 id 확인
YouTube Microsoft Developer 채널 > 재생목록탭 > 영상 클릭하면 url에서 재생목록 id(붉은색 표시)를 확인할 수 있다.
https://www.youtube.com/watch?v=PqdkxcMdBHY&list=PLlrxD0HtieHgS6P6YBu3Bc1DA9TICZ9CM
Octopus Deploy라는 재생목록의 영상을 클릭했고, 해당 재생목록의 id가 PLlrxD0HtieHgS6P6YBu3Bc1DA9TICZ9CM 임을 알 수 있다.
4. 재생목록 동영상리스트 api를 호출해보자.
YouTube Data API 문서 :
https://developers.google.com/youtube/v3/docs/playlistItems
아래와 같은 json 형태의 데이터를 전달 받는다.
이중에서 publishedAt, title, thumbnails의 midium url, resourceId의 videoId 값만 리스트로 추출해보자.
{
"kind": "youtube#playlistItemListResponse",
"etag": "AleZ0ULSZMDuAhZXvcAm1x0GOL4",
"items": [
{
"kind": "youtube#playlistItem",
"etag": "KvanKcR_TGplc07URPDpxsja39Q",
"id": "UExscnhEMEh0aWVIZ1M2UDZZQnUzQmMxREE5VElDWjlDTS41NkI0NEY2RDEwNTU3Q0M2",
"snippet": {
"publishedAt": "2022-06-15T12:31:57Z",
"channelId": "UCsMica-v34Irf9KVTh6xx-g",
"title": "Infrastructure as Code on Azure with Microsoft and Octopus Deploy (APAC)",
"description": "Microsoft Azure is a leading cloud provider that releases new services daily. We host Octopus Cloud on the Azure Kubernetes Service (AKS). We use Terraform and other Infrastructure as Code (IaC) languages to deploy Octopus Cloud.\n\nIn this webinar, Mark Gray, Principal Program Manager at Microsoft in the Azure Deployment team, will join Derek Campbell, and they will discuss and show you some of the many ways you can deploy your infrastructure to Azure using Infrastructure as Code.\n\nYou will learn:\n\n- About Infrastructure as Code on Azure\n- The different ways to define IaC on Azure\n- How to deploy an Azure web app and resource group using different IaC languages and approaches",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/PqdkxcMdBHY/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/PqdkxcMdBHY/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/PqdkxcMdBHY/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Microsoft Developer",
"playlistId": "PLlrxD0HtieHgS6P6YBu3Bc1DA9TICZ9CM",
"position": 0,
"resourceId": {
"kind": "youtube#video",
"videoId": "PqdkxcMdBHY"
},
"videoOwnerChannelTitle": "Microsoft Developer",
"videoOwnerChannelId": "UCsMica-v34Irf9KVTh6xx-g"
}
},
{
"kind": "youtube#playlistItem",
"etag": "AjChdjw3tUKub5_OBN01bqhokkA",
"id": "UExscnhEMEh0aWVIZ1M2UDZZQnUzQmMxREE5VElDWjlDTS4yODlGNEE0NkRGMEEzMEQy",
"snippet": {
"publishedAt": "2022-06-15T12:32:33Z",
"channelId": "UCsMica-v34Irf9KVTh6xx-g",
"title": "CI/CD With GitHub Action And Octopus Deploy",
"description": "GitHub Actions offers a highly flexible environment to integrate with source control, build application artifacts, and prepare packages for deployment using Octopus Deploy.\n\nIn this webinar, Pete Gallagher will be joined by Chris Reddington, Azure Cloud Architect at Microsoft UK. They’ll walk you through combining GitHub Actions and Octopus to create infrastructure and build and deploy applications.\n\nLearn how to:\n\n- Configure GitHub Actions to integrate with source control and trigger actions based on changes to the code base\n- Build the application source of a web app and deliver artifacts to Octopus Deploy for deployment to Azure\n- Use Octopus Runbooks to provision infrastructure in Azure\n- Deploy applications to Azure with Octopus\n\n0:00 Introduction\n2:48 Agenda\n3:59 Introduction to GitHub\n7:55 GitHub Codespaces\n9:51 GitHub Actions\n11:54 GitHub Actions Marketplace\n12:30 GitHub Actions and Octopus Deploy\n15:14 GitHub Code Scanning\n17:56 Demo - GitHub Codespaces\n23:34 Demo - GitHub Actions\n32:50 Demo - GitHub Actions and Octopus Deploy\n35:44 Demo - Octopus Deploy Release Process\n40:00 Demo - Octopus Deploy Config as Code\n44:34 Recap\n47:35 Q&A\n58:03 Final Slides",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/DhhcVr--kWs/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/DhhcVr--kWs/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/DhhcVr--kWs/hqdefault.jpg",
"width": 480,
"height": 360
},
"standard": {
"url": "https://i.ytimg.com/vi/DhhcVr--kWs/sddefault.jpg",
"width": 640,
"height": 480
},
"maxres": {
"url": "https://i.ytimg.com/vi/DhhcVr--kWs/maxresdefault.jpg",
"width": 1280,
"height": 720
}
},
"channelTitle": "Microsoft Developer",
"playlistId": "PLlrxD0HtieHgS6P6YBu3Bc1DA9TICZ9CM",
"position": 1,
"resourceId": {
"kind": "youtube#video",
"videoId": "DhhcVr--kWs"
},
"videoOwnerChannelTitle": "Octopus Deploy",
"videoOwnerChannelId": "UCURDSDCwx9ZiCMcLdc8d6Uw"
}
},
{
"kind": "youtube#playlistItem",
"etag": "SXqFPTMdAeQ0OW3bALTsyzarpFo",
"id": "UExscnhEMEh0aWVIZ1M2UDZZQnUzQmMxREE5VElDWjlDTS4wMTcyMDhGQUE4NTIzM0Y5",
"snippet": {
"publishedAt": "2022-06-17T06:49:54Z",
"channelId": "UCsMica-v34Irf9KVTh6xx-g",
"title": "Azure Arc and Octopus Deploy (APAC)",
"description": "Azure Arc lets you manage and secure infrastructure and apps running anywhere as if they were resources in the Azure public cloud.\n\nIn this webinar, Sarah Lean will be joined by Thomas Maurer, Senior Program Manager, Microsoft Azure Hybrid. They’ll give you a rundown of Azure Arc and show you how to onboard resources created in Octopus Runbooks to Azure Arc.\n\nJoin Sarah and Thomas to learn: \n\n- The capabilities of Azure Arc\n- Benefits of using Azure Arc\n- How to use Octopus Runbooks to install the Azure Arc agent",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/5hYOC8DIrTg/default_live.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/5hYOC8DIrTg/mqdefault_live.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/5hYOC8DIrTg/hqdefault_live.jpg",
"width": 480,
"height": 360
},
"standard": {
"url": "https://i.ytimg.com/vi/5hYOC8DIrTg/sddefault_live.jpg",
"width": 640,
"height": 480
},
"maxres": {
"url": "https://i.ytimg.com/vi/5hYOC8DIrTg/maxresdefault_live.jpg",
"width": 1280,
"height": 720
}
},
"channelTitle": "Microsoft Developer",
"playlistId": "PLlrxD0HtieHgS6P6YBu3Bc1DA9TICZ9CM",
"position": 2,
"resourceId": {
"kind": "youtube#video",
"videoId": "5hYOC8DIrTg"
},
"videoOwnerChannelTitle": "Microsoft Developer",
"videoOwnerChannelId": "UCsMica-v34Irf9KVTh6xx-g"
}
}
],
"pageInfo": {
"totalResults": 3,
"resultsPerPage": 50
}
}
5. Model class 생성
using System;
namespace MW.Objects.DTO
{
public class VOBoard
{
public class playitem
{
public string title { get; set; }
public string thumbnail { get; set; }
public DateTime date { get; set; }
public string videoId { get; set; }
}
}
}
6. HttpWebRequest로 api 호출하는 함수 생성
public static string CallYouTubeWebClient(string playlistId) {
string requestKey = "발급받은 키 입력";
string url = string.Format("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&status=&playlistId={0}&key={1}", playlistId, requestKey);
string strResponse = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
HttpStatusCode status = resp.StatusCode;
if (status == HttpStatusCode.OK) {
Stream respStream = resp.GetResponseStream();
using (StreamReader sr = new StreamReader(respStream))
{
strResponse = sr.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
}
return strResponse;
}
7. 호출하여 Object List로 변환하기
List<playitem> playitems = new List<playitem>();
string strResponse = CallYouTubeWeb("PLlrxD0HtieHgS6P6YBu3Bc1DA9TICZ9CM");
dynamic response = JsonConvert.DeserializeObject<dynamic>(strResponse);
try
{
var query = from item in ((IEnumerable)response.items).Cast<dynamic>()
select new playitem { title = item?.snippet?.title, thumbnail = item?.snippet?.thumbnails?.medium?.url, date = Convert.ToDateTime(item?.snippet?.publishedAt), videoId = item?.snippet?.resourceId?.videoId };
playitems = query.ToList<playitem>();
playitems.AddRange(query.ToList<playitem>());
}
catch (Exception ex)
{
}
item?.snippet?.title에서 ?.은 Null 조건부 연산자로 item이 not-null일때만 다음 member access를 실행하고, 아니면 null을 반환한다.
item.snippet.thumbnails.medium.url에 medium property가 없는 경우, 에러("null 참조에 대해 런타임 바인딩을 수행할 수 없습니다.")처리되어 catch로 넘어간다.
playitems에는 아무것도 담기지 않는다.
item?.snippet?.thumbnails?.medium?.url에 medium property가 없는 경우, thumbnail만 null값이고 다른 peroperty는 값이 정상 저장되어 playitems에 데이터가 추가된다.
Null 조건부 연산자는 ?., ?[] 가 있다.
- a가 null로 평가되면 a?.x 또는 a?[x]의 결과는 null입니다.
- a가 null이 아닌 것으로 평가되면 a?.x 또는 a?[x]의 결과는 각각 a.x 또는 a[x]의 결과와 같습니다.
'C#' 카테고리의 다른 글
C#] 코드 성능 분석 BenchmarkDotNet (0) | 2022.07.05 |
---|---|
C#] Anonymous Type(무명 형식) 정의, 사용법, Dynamic Type과 비교 (0) | 2022.06.28 |
C# 9, 10) record의 정의, 사용법, class와 다른 점 (0) | 2022.01.06 |
C#] LINQ to XML(XDocument) vs XML DOM(XmlDocument) (0) | 2022.01.04 |
C#] Value type은 어디에 저장되는가? Stack or Heap?? (0) | 2021.12.24 |
댓글