How do I check if a YouTube video exists using the YouTube API in Java?

Viewed 437

I am looking for some form of boolean function which takes a YouTube video link/ID as an input, and returns whether or not the video exists, such as:

if(!videoExists(youtube.com/testvideo)) {
    print("Error - video does not exist")
}

Is this at all possible? Thanks.

1 Answers

You can use Videos:List and specify the video ID to retrieve video information for a specific video. For example:

YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(),
        new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("video-test").build();

String videoId = "Mp-oorqKnjR";
YouTube.Videos.List videoRequest = youtube.videos().list("snippet,statistics,contentDetails");
videoRequest.setId(videoId);
videoRequest.setKey("<YOUR_API_KEY>");
VideoListResponse listResponse = videoRequest.execute();
List<Video> videoList = listResponse.getItems();

Video targetVideo = videoList.iterator().next();

then go over targetVideo would then hold information related to your video. You can get information such as title, view count and duration from this object I would guess that if the video doesn't exist you'll have some null or some sort of empty object form that you could determine the video existence from that.

imports:

import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoListResponse;
Related