Select Page

Using the YouTube Data API V3, you can create a C# function to connect to the YouTube API, retrieve the first video result, and return an image along with the video title.

Below is an example of a C# function that could be used to achieve this:

public async Task<(string title,string imageUrl)> RetrieveFirstVideo()
{
// Create a new YouTubeService instance.
var youtubeService = new YouTubeService(new BaseClientService.Initializer());

// Create a new SearchResource instance.
var searchResource = youtubeService.Search;

// Define a list to store the results of the search query.
var searchResults = new List();

// Create a new ListRequest instance.
var listRequest = searchResource.List(“snippet”);

// Set the q parameter of the ListRequest instance to your search query.
listRequest.Q = “YourSearchQuery”;

// Execute the search query and return the results in the list.
searchResults = await listRequest.ExecuteAsync();

// Return the first result from the search results.
var videoResult = searchResults.FirstOrDefault();
if (videoResult != null)
{
return (videoResult.Snippet.Title, videoResult.Snippet.Thumbnails.Default.Url);
}

// If no results were returned, return null.
return (null, null);
}