satish kumar V
satish kumar V

Reputation: 1755

youtube api in c# code

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("https://www.googleapis.com/youtube/v3/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage response = client.GetAsync("search?q=manam&type=video&order=relevance&part=snippet&maxResults=50&key=AIzaSyA4GZFAgfvsAItwFRmnAZvbTHoDeyunf2k").Result;
    if (response.IsSuccessStatusCode)
    {
        dynamic lists = await response.Content.ReadAsAsync<mycustomObject>(); // what should I write here
    } 
}

I am trying to get the youtube videos with web api call in my project. This is the code what I tried till now, to get the response what should I use in the place of myCustomObject ?

when I am trying with the above url in browser I am getting the data, when I ran above code it return null,

Anything wrong with above code?

I just want to get the data from this method,

Any help will be greatly appreciated.

Upvotes: 1

Views: 654

Answers (1)

RagtimeWilly
RagtimeWilly

Reputation: 5445

You need a class which represents the JSON data being returned from the call.

If you call your GET request in a browser you'll see the JSON response looks something like this:

{
    kind: "youtube#searchListResponse"
    etag: ""tbWC5XrSXxe1WOAx6MK9z4hHSU8/lh-waoy9ByBY2eB-oZs7niK51FU""
    nextPageToken: "CDIQAA"
    pageInfo: 
        {
            totalResults: 176872
            resultsPerPage: 50
        }-
    items: [...50]-
}

So you need to create a class with matching fields which the deserialize command will then populate for you. Something like this:

public class YoutubeApiResponse()
{
    public string kind {get; set;}
    public string etag {get; set;}
    public string nextPageToken {get; set;}
    public PageInfo pageInfo {get; set;}
    public List<Item> items {get; set;}
}

And call like this:

var youtubeResponse = await response.Content.ReadAsAsync<YoutubeApiResponse().Result();

I'd recommend looking at the .Net Client Library - it will take care of a lot of this stuff for you.

Upvotes: 3

Related Questions