How to pull weather info into a console app using OpenWeatherMap API

In this post, I’m going to show you how to pull weather data from a web service in a console application in easy to follow steps.

First things first, let’s sign up with Weather Map using this link.

After you have signed up, go to the API keys tab as in the image below. Here, you will see a default API key generated. If it’s not there, you can generate one by simply entering a key name in the *Name field and hitting the Generate button:

You can create however many API keys you want, although, you would only need one.

Once you have obtained a key, it takes somewhere between 10 to 60 minutes for the key to activated, so be patient!!

Next, let’s first test the API key using Postman or Fiddler, although, I’m using Postman here. If you don’t have Postman, you can install it from this link.

If you rather use your favorite browser, you can simply use the URL below in the address bar:

api.openweathermap.org/data/2.5/weather?q=london&appid={my_api_key}

Please note, I have chosen to have the web service return me JSON data. If you are comfortable with XML, you can do so by specifying mode=xml or even html in the URI. Otherwise, used mode=json like the one that is being used here. This is the beauty of RESTful services where one of its tenets is content negotiation.

Another cool trick is to have Visual Studio generate a C# POCO class from a JSON object string. To do that, simply copy the JSON raw data, then in Visual Studio IDE, go to Edit -> Past Special -> Paste JSON As Classes. See below:

Alternatively, you can use this tool to do just the same. Below is the class that would get generated using one of the above methods:

public class RootObject
    {
        public Coord coord { get; set; }
        public Weather[] weather { get; set; }
        public string _base { get; set; }
        public Main main { get; set; }
        public int visibility { get; set; }
        public Wind wind { get; set; }
        public Clouds clouds { get; set; }
        public int dt { get; set; }
        public Sys sys { get; set; }
        public int id { get; set; }
        public string name { get; set; }
        public int cod { get; set; }
    }

    public class Coord
    {
        public float lon { get; set; }
        public float lat { get; set; }
    }

    public class Main
    {
        public float temp { get; set; }
        public int pressure { get; set; }
        public int humidity { get; set; }
        public float temp_min { get; set; }
        public float temp_max { get; set; }
    }

    public class Wind
    {
        public float speed { get; set; }
        public int deg { get; set; }
        public float gust { get; set; }
    }

    public class Clouds
    {
        public int all { get; set; }
    }

    public class Sys
    {
        public int type { get; set; }
        public int id { get; set; }
        public float message { get; set; }
        public string country { get; set; }
        public int sunrise { get; set; }
        public int sunset { get; set; }
    }

    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }

Next, let’s write some code that will deserialize raw JSON string into a C# object that is shown above.

private async static Task GetJsonWeatherData(string location, string apikey)
        {
            string url = $"http://api.openweathermap.org/data/2.5/weather?q=" + location +
                       $"&mode=json&units=metrics&APPID=" + apikey;
            try
            {
                using (var webClient = new WebClient())
                {
                    var rawJSON = await webClient.DownloadStringTaskAsync(url);
                    RootObject root = JsonConvert.DeserializeObject(rawJSON);
                    return root;
                }
            }
            catch (AggregateException ae)
            {
                throw ae;
            }
        }

Having tested the api from inside PostSharp, it’s time to call the above method from Program Main of our console app like so:

You might also want to import the following namespaces:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;

 

    static void Main(string[] args)
        {
            string apiKey = "hhdfda63316dfkeytrtbde96d94545454545lkl";
            var root = GetJsonWeatherData("toronto,ca", apiKey).GetAwaiter().GetResult();

            Console.WriteLine("City: " + root.name);
            Console.WriteLine("Current Temperature: " + string.Format("{0}\u00B0C", Math.Round(ConvertKelvinToCelcius(root.main.temp))));
            Console.WriteLine("Minimum: " + string.Format("{0}\u00B0C", Math.Round(ConvertKelvinToCelcius(root.main.temp_min))));
            Console.WriteLine("Maximum: " + string.Format("{0}\u00B0C", Math.Round(ConvertKelvinToCelcius(root.main.temp_max))));          
            Console.ReadLine();            
        }
        private static double ConvertKelvinToFahrenheit(float temperature)
        {
            double myTemp;
            myTemp = ((temperature - 273.15) * 9 / 5) + 32;
            return myTemp;
        }

        private static double ConvertKelvinToCelcius(float temperature)
        {
            double myTemp;
            myTemp = (temperature - 273.15);
            return myTemp;
        }

Now run the program in Visual Studio to verify the output. Here, you can see a subset ofΒ  data being pulled from a web service that is exposed by OpenWeatherMap API. Although, there’s a lot of data that you could show here such as wind, humidity etc., however, for the purposes of demonstration, I am only showing values that are relevant for this exercise.

Hope you liked it! πŸ™‚

About Obi Oberoi

Obi Oberoi is an Independent Consultant, Developer and a Life-Long student of continuous learning. Obi enjoys to code, read, and hang out with techies and geeks!
This entry was posted in .NET, Web Services. Bookmark the permalink.