Search code examples
c#asp.net-coreconsoleasp.net-core-2.0

Net Core Simple way to Find Temperature from Openweather API


I just started programming. What is a simple way to grab the temperature and display it on screen? I want to write a simple program.

static void Main()
{

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://api.openweathermap.org");
    var response = client.GetAsync($"/data/2.5/weather?q=London,UK&appid={APIKey}&units=metric");

    // What do I place here??


    Console.WriteLine(Main.Temp);


}

Solution

  • There are 2 concepts you need to consider here:

    Asynchronous programming

    HttpClient.GetAsync() is an asynchronous method. There is a nice walk-through of working with async APIs in Microsoft's documentation.

    But the gist of it is that method doesn't return the data from the endpoint. It returns a "promise"; something that represents the data that will be available at a future time. Since your program isn't doing any other things, you can just await the result, like so:

    var response = await client.GetAsync();
    

    But of course, you need to first make the enclosing method async. In your case, change the signature of your Main() function to:

    static async Task Main(string[] args)
    

    JSON Deserialization

    The endpoint you're calling returns its data in JSON format. Since you're just learning, I wouldn't bother trying to find an actual schema or client library.

    What you should do instead is to create a class with properties for each of the fields in the response, and deserialize into it, as shown here: https://www.newtonsoft.com/json/help/html/DeserializeObject.htm