1

I'm trying to make a program in windows forms that can search for movies and series trough a web api. The program then needs to display all relevant information onto a form.

I got stuck getting the program to read from the web api. After a lot of searching i decided to put it up here.

I have some code which is mostly based on this article: https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new App());
    }

    static HttpClient client = new HttpClient();

    static async Task RunAsync()
    {
        // Update port # in the following line.
        client.BaseAddress = new Uri("http://www.omdbapi.com/?apikey=caa4fbc9&t=it");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

    }

    static async Task<Film> GetFilmAsync(string path)
    {
        Film film = null;
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {
            film = await response.Content.ReadAsAsync<Film>();
        }
        return film;
    }
}

Sadly it doesn't do much and i don't have any clue on what to do next. So as i said this should read data from a web api(http://www.omdbapi.com/). Then it has to put the selected items into a class which i can then use to make up the form.

public class Film
{
    public string Title { get; set; }
    public string Released { get; set; }
    public string Runtime { get; set; }
    public string Genre { get; set; }
    public string Director { get; set; }
    public string Actors { get; set; }
    public string Plot { get; set; }
    public string Language { get; set; }
    public string imdbRating { get; set; }
    public string totalSeasons { get; set; }
    public string Type { get; set; }
}

I hope anyone can help! Anything is appreciated!

NDC
  • 29
  • 1
  • 1
  • 7

1 Answers1

1

I have changed a bit your code and it seems to work well:

async void Main()
{
    await InitClient();

    // Pass the file title to the API
    var result = await GetFilmAsync("it");
    client.CancelPendingRequests();
    client.Dispose();    
}

// Changed name to be more meaningful 
static async Task InitClient()
{
    // Remove the part with your key and the film title from the general initialization
    client.BaseAddress = new Uri("http://www.omdbapi.com/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

}

static async Task<Film> GetFilmAsync(string title)
{
    Film film = null;

    // Compose the path adding the key and the film title
    string path = "?apikey=caa4fbc9&t=" + title;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        string data = await response.Content.ReadAsStringAsync();

        // This is the key point, the API returns a JSON string
        // You need to convert it to your Film object.
        // In this example I have used the very useful JSon.NET library
        // that you can easily install with NuGet.
        film = JsonConvert.DeserializeObject<Film>(data);
    }
    return film;
}
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Hi, thank you for the answer. I can't seem to get the `JsonConvert` to work even though the nuget json package was already installed. The package "Newtonsoft.Json" is installed. Also the "await" gives the following error: "The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task' " @Steve – NDC Aug 24 '19 at 13:18
  • About the Json.Net. Did you add the required using statements? About the async. The Main method should be marked async, but that was my mistake to show a call example – Steve Aug 24 '19 at 13:21
  • I did all of that and it works now. Thank you so much for the help! – NDC Aug 24 '19 at 13:44
  • JsonConvert,Deserialize will try to extract the data from the json string returned by the API and create an instance of the object requested putting everything that matches into the matching properties of your Film class – Steve Aug 24 '19 at 13:44
  • Ok thank you for the explanation, this made it very clear! – NDC Aug 24 '19 at 14:00