목차 ▽열기
문제
YouTube 검색 활용한 서버 개발
1. API 개요
- YouTube Data API를 활용하여 키워드 기반으로 동영상을 검색하는 API
- 검색 결과는 최신순으로 20개의 동영상 정보를 반환
2. API 엔드포인트
- URL: /api/v1/video/search
- Method: GET
- Content-Type: application/json
3. 요청 파라미터
Query Parameters
파라미터명 타입 필수여부 설명 예시
keyword | String | Y | 검색할 키워드 | "여행" |
4. 응답 형식
Success Response (200 OK)
{
"totalCount": 20,
"videos": [
{
"videoId": "비디오 ID",
"title": "영상 제목",
"videoUrl": "유튜브 영상 URL",
"thumbnailUrl": "썸네일 URL",
"channelTitle": "채널명",
"publishedAt": "업로드 날짜(YYYY-MM-DD HH:mm:ss)",
"viewCount": 1234567
}
]
}
응답 필드 설명
필드명 타입 설명
totalCount | Integer | 검색된 총 동영상 수 |
videos | Array | 검색된 동영상 목록 |
videos[].videoId | String | 유튜브 동영상 고유 ID |
videos[].title | String | 동영상 제목 |
videos[].videoUrl | String | 유튜브 영상 URL (예: https://www.youtube.com/watch?v={videoId}) |
videos[].thumbnailUrl | String | 썸네일 이미지 URL |
videos[].channelTitle | String | 채널명 |
videos[].publishedAt | String | 업로드 날짜 |
videos[].viewCount | Integer | 조회수 |
Error Response (4xx/5xx)
- 400 Bad Request: 잘못된 요청 파라미터
- 500 Internal Server Error: 서버 내부 오류 또는 YouTube API 호출 실패
6. 요청 예시
GET /api/v1/video/search?keyword=여행
7. 제한사항
- 한 번의 요청당 최대 20개의 동영상 정보 제공
- YouTube Data API의 일일 할당량 제한을 따름
- 키워드는 URL 인코딩되어 전송되어야 함
프로젝트 생성하기
스프링 이니셜라이저
web, lombok
google-api-services-youtube 라이브러리는 Spring Initializr에서 제공하지 않습니다.
이 라이브러리는 Google에서 공식적으로 제공하는 YouTube Data API v3 클라이언트 라이브러리입니다.
이 라이브러리는 다음 공식 문서에서 찾을 수 있습니다:
- Google YouTube Data API 공식 문서:
https://developers.google.com/youtube/v3/getting-started
https://developers.google.com/youtube/v3/quickstart/java
- Maven Central Repository:
https://mvnrepository.com/artifact/com.google.apis/google-api-services-youtube
사용하기 위한 단계:
- Google Cloud Console에서 프로젝트 생성
- YouTube Data API v3 활성화
- API 키 발급
- Maven/Gradle 의존성 추가
- API 클라이언트 코드 구현
풀이
SpringBoot 세팅

Github와 클론 진행

intelliJ

https://mvnrepository.com/artifact/com.google.apis/google-api-services-youtube/v3-rev117-1.17.0-rc

<!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-youtube -->
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-youtube</artifactId>
<version>v3-rev222-1.25.0</version>
</dependency>

동기화및 로드 재시작진행해줍니다.


사용하기 위한 단계:
- Google Cloud Console에서 프로젝트 생성
- YouTube Data API v3 활성화
- API 키 발급
- Maven/Gradle 의존성 추가
- API 클라이언트 코드 구현
62. [ JAVA ] Spring Boot를 이용한 API 통신 : 유튜브 API 세팅
62. [ JAVA ] Spring Boot를 이용한 API 통신 : 유튜브 API 세팅
유튜브 API 세팅 1. 새 프로젝트 생성 Youtube API키를 발급받기 위해서는 먼저 Google Cloud에서 새 프로젝트를 생성해야합니다. Google Cloud 플랫폼 바로가기 Google 클라우드 플랫폼로그인 Google 클
danmi1109.tistory.com

spring:
profiles:
active: dev
youtube:
api:
key: Google API key
1. API 개요
- YouTube Data API를 활용하여 키워드 기반으로 동영상을 검색하는 API
- 검색 결과는 최신순으로 20개의 동영상 정보를 반환
2. API 엔드포인트
- URL: /api/v1/video/search
- Method: GET
- Content-Type: application/json
3. 요청 파라미터
Query Parameters
파라미터명 타입 필수여부 설명 예시
keyword | String | Y | 검색할 키워드 | "여행" |
Postman

필드명 타입 설명
totalCount | Integer | 검색된 총 동영상 수 |
videos | Array | 검색된 동영상 목록 |
videos[].videoId | String | 유튜브 동영상 고유 ID |
videos[].title | String | 동영상 제목 |
videos[].videoUrl | String | 유튜브 영상 URL (예: https://www.youtube.com/watch?v={videoId}) |
videos[].thumbnailUrl | String | 썸네일 이미지 URL |
videos[].channelTitle | String | 채널명 |
videos[].publishedAt | String | 업로드 날짜 |
videos[].viewCount | Integer | 조회수 |
Error Response (4xx/5xx)
- 400 Bad Request: 잘못된 요청 파라미터
- 500 Internal Server Error: 서버 내부 오류 또는 YouTube API 호출 실패
6. 요청 예시
GET /api/v1/video/search?keyword=여행

intelliJ
config패키지 - YouTubeConfig 클래스 생성

@Configuration
public class YouTubeConfig {
@Bean
public YouTube youTube() throws Exception{
return new YouTube.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
null
).setApplicationName("video-server").build();
}
}
controller 패키지 생성 - VideoController 클래스 생성

@RestController
public class VideoController {
@Autowired
VideoService videoService;
@GetMapping("/api/v1/video/search")
getVideos(@RequestParam("keyword") String keyword){
videoService.getVideos(keyword);
service패키지 생성 - VideoService 클래스 생성
위의 링크에서 Youtube API 호출에 대한 가이드와 여러 샘플 코드를 참고할 수 있습니다.
필드명 타입 설명
totalCount | Integer | 검색된 총 동영상 수 |
videos | Array | 검색된 동영상 목록 |
videos[].videoId | String | 유튜브 동영상 고유 ID |
videos[].title | String | 동영상 제목 |
videos[].videoUrl | String | 유튜브 영상 URL (예: https://www.youtube.com/watch?v={videoId}) |
videos[].thumbnailUrl | String | 썸네일 이미지 URL |
videos[].channelTitle | String | 채널명 |
videos[].publishedAt | String | 업로드 날짜 |
videos[].viewCount | Integer | 조회수 |
Error Response (4xx/5xx)
- 400 Bad Request: 잘못된 요청 파라미터
- 500 Internal Server Error: 서버 내부 오류 또는 YouTube API 호출 실패

4. 응답 형식
Success Response (200 OK)
{
"totalCount": 20,
"videos": [
{
"videoId": "비디오 ID",
"title": "영상 제목",
"videoUrl": "유튜브 영상 URL",
"thumbnailUrl": "썸네일 URL",
"channelTitle": "채널명",
"publishedAt": "업로드 날짜(YYYY-MM-DD HH:mm:ss)",
"viewCount": 1234567
}
]
}
응답 필드 설명
dt0패키지 생성 - VideoListResponse 클래스 생성

@Data
@NoArgsConstructor
@AllArgsConstructor
public class VideoListResponse {
public Integer totalCount;
public List<VideoResponse> videos;
}
VideoResponse 클래스 생성

@Data
@NoArgsConstructor
@AllArgsConstructor
public class VideoResponse {
public String videoId;
public String title;
public String videoUrl;
public String thumbnailUrl;
public String channelTitle;
public String publishedAt;
public Long viewCount;
}



@Service
public class VideoService {
@Autowired
YouTube youTube;
@Value("${youtube.api.key}")
String apiKey;
public com.example.dto.VideoListResponse getVideos(String keyword){
// 유투브 검색 api 명세서 확인.
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 searchResponse = search.execute();
List<SearchResult> searchResults = searchResponse.getItems();
// 비디오 ID 목록 생성
List<String> videoIds = new ArrayList<>();
for( SearchResult result : searchResults){
videoIds.add( result.getId().getVideoId() );
}
// 비디오의 정보를 요청.
// statistics,snippet 으로 요청!
// 비디오의 통계 데이터(조회수, 좋아요 수)와 기본정보(제목,설명,썸네일)
YouTube.Videos.List videoRequest =
youTube.videos().list("statistics,snippet");
videoRequest.setKey(apiKey);
videoRequest.setId( String.join(",", videoIds) );
// 요청 실행
VideoListResponse videoResponse = videoRequest.execute();
List<Video> videoList = videoResponse.getItems();
// 우리 DTO로 변환해서 컨트롤러에 리턴.
List<VideoResponse> videoResponseList = new ArrayList<>();
for ( Video video : videoList){
VideoResponse videoResponse1 = new VideoResponse();
videoResponse1.videoId = video.getId();
videoResponse1.title = video.getSnippet().getTitle();
videoResponse1.videoUrl =
"https://www.youtube.com/watch?v=" + video.getId();
videoResponse1.thumbnailUrl =
video.getSnippet().getThumbnails().getHigh().getUrl();
videoResponse1.channelTitle =
video.getSnippet().getChannelTitle();
videoResponse1.publishedAt =
video.getSnippet().getPublishedAt().toString();
videoResponse1.viewCount =
video.getStatistics().getViewCount().longValue();
videoResponseList.add(videoResponse1);
}
com.example.dto.VideoListResponse videoListResponse =
new com.example.dto.VideoListResponse();
videoListResponse.totalCount = videoResponseList.size();
videoListResponse.videos = videoResponseList;
return videoListResponse;
} catch (IOException e) {
throw new RuntimeException();
}
}
}
Postman
'API > 실습' 카테고리의 다른 글
76. [JAVA] API 문서 문제 : JDBC -> JPA 진행 (1) (0) | 2025.01.14 |
---|---|
69. [ JAVA ] 공공데이터 포털 API 이용 : 영화 박스오피스순위 예시 (0) | 2025.01.13 |
61. [ JAVA ] API 리뷰 작성시 사진 추가 업로드 구현 (0) | 2025.01.12 |
55. [ JAVA ] API 문서 문제 : JWT(Json Web Token)(보안) / Admin(2) (1) | 2025.01.11 |
53. [ JAVA ] Spring Boot를 이용한 API 통신 : 뉴스 검색 예시 (1) | 2025.01.11 |