구글 API 공식문서
https://developers.google.com/youtube/v3/getting-started
https://developers.google.com/youtube/v3/quickstart/java
https://developers.google.com/api-client-library/java?hl=ko
API Client Library for Java | Google for Developers
Google에서 작성한 자바용 Google API 클라이언트 라이브러리는 Google API에 액세스하기 위한 간단하고 유연한 자바 라이브러리입니다.
developers.google.com
라이브러리를 받아와서 복붙해준다.
메이븐 동기화를 시켜주면 빨간색이 없어진다
https://developers.google.com/youtube/v3/docs/search/list?hl=ko
Search: list | YouTube Data API | Google for Developers
이 페이지는 Cloud Translation API를 통해 번역되었습니다. Search: list 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. API 요청에 지정된 쿼리 매개변수와 일치하는
developers.google.com
설명서에 맞춰 서비스를 작성하겠다. 위에 링크는 설명서이다
이제 전체 보낼 리스판스만든다
@Service
public class VideoService {
@Autowired
YouTube youtube;
@Value("${youtube.api.key}")
String apiKey;
public com.qoeka98.video.dto.VideoListResponse getVideo(String keyword) {
try {
// 검색 요청 설정
YouTube.Search.List search = youtube.search().list("id,snippet");
search.setKey(apiKey);
search.setQ(keyword);
search.setType("video");
search.setMaxResults(20L);
search.setOrder("date"); // 최신 순으로 정렬
// 검색 실행
SearchListResponse searchListResponse = search.execute();
List<SearchResult> searchResults = searchListResponse.getItems();
// 비디오 ID 목록 생성
List<String> videoIds = new ArrayList<>();
for (SearchResult searchResult : searchResults) {
videoIds.add(searchResult.getId().getVideoId());
}
// 비디오 정보 요청 설정
YouTube.Videos.List videoRequest = youtube.videos().list("statistics,snippet");
videoRequest.setKey(apiKey);
videoRequest.setId(String.join(",", videoIds));
// 비디오 정보 요청 실행
VideoListResponse videoListResponse = videoRequest.execute();
List<Video> videoList = videoListResponse.getItems();
//우리 DTO로 변환해서 컨트롤러에 리턴
List<VideoResponse> videoResponsesList = new ArrayList<>();
for (Video video : videoList) {
VideoResponse videoResponse = new VideoResponse();
videoResponse.videoId = video.getId();
videoResponse.title = video.getSnippet().getTitle();
videoResponse.videoUrl = "https://www.youtube.com/watch?v=" + video.getId();
videoResponse.thumbnailUrl = video.getSnippet().getThumbnails().getHigh().getUrl();
videoResponse.channelTitle = video.getSnippet().getChannelTitle();
videoResponse.publishedAt = video.getSnippet().getPublishedAt().toString();
videoResponse.viewCount = video.getStatistics().getViewCount().longValue();
videoResponsesList.add(videoResponse);
}
com.qoeka98.video.dto.VideoListResponse videoListResponse1 = new com.qoeka98.video.dto.VideoListResponse();
videoListResponse1.totalContent = videoList.size();
videoListResponse1.video = videoResponsesList;
return videoListResponse1;
} catch (IOException e) {
throw new RuntimeException("YouTube API 호출 실패", e);
}
}}
'Spring Boot JPA > 실습' 카테고리의 다른 글
파이썬 : 로지스틱 리그레이션 (0) | 2025.01.28 |
---|---|
박스오피스 OPEN API 실습과 배포 (0) | 2025.01.13 |
여행코스 공유 플랫폼 JPA (0) | 2025.01.09 |
JPA Join과 Config 설정으로 데이터베이스 관계 정리2 (0) | 2025.01.08 |
JPA Join과 Config 설정으로 데이터베이스 관계 정리 (0) | 2025.01.07 |