Skip to content

Sample Retrieving some Weather data from a 3rd party REST API

Pure Krome edited this page Nov 10, 2016 · 6 revisions

Sample - Retrieving some Weather data from an 3rd party REST API

What: retrieve some weather data from a 3rd party REST API

Why: to show all full, working end to end code scenario.

Here is the full code. It's also available as a gist.

using System;
using System.Threading.Tasks;
using WorldDomination.Net.Http;

namespace HttpClient.Helpers.SampleConsoleApplication
{
    public class Program
    {
        private const string MebourneWeatherApiEndpoint =
            "http://api.openweathermap.org/data/2.5/weather?q=Melbourne,AU";
        private const string DefaultKey = "pewpew";

        private static void Main(string[] args)
        {
            Console.WriteLine("Starting sample console application.");
            Console.WriteLine("");
            Console.WriteLine("");

            Console.WriteLine("About to retrieve weather for Melbourne, Australia...");
            var json = GetCurrentWeather().Result;
            Console.WriteLine("Retrieved some result form the weather service ...");
            Console.WriteLine("");
            Console.WriteLine("{0}", json);
            Console.WriteLine("");

            Console.WriteLine("About to retrieve some fake weather result ...");
            var fakeResult = GetFakeWeather().Result;
            Console.WriteLine("Retrieved some fake result ...");
            Console.WriteLine("");
            Console.WriteLine("{0}", fakeResult);
            Console.WriteLine("");

            Console.WriteLine("End of sample console application. Thank you for trying this out :)");
            Console.WriteLine("");

        }

        private static async Task<string> GetCurrentWeather()
        {
            var requestUri = new Uri(MebourneWeatherApiEndpoint);

            string content;
            using (var httpClient = HttpClientFactory.GetHttpClient(DefaultKey))
            {
                content = await httpClient.GetStringAsync(requestUri);
            }

            return content;
        }

        private static async Task<string> GetFakeWeather()
        {
            // Set up the fake response for the Weather API Endpoint.
            var messageResponse = FakeHttpMessageHandler.GetStringHttpResponseMessage("I am some fake weather result");
            var messageHandler = new FakeHttpMessageHandler(MebourneWeatherApiEndpoint, messageResponse);
            HttpClientFactory.AddMessageHandler(messageHandler, DefaultKey);
 
            // Now attempt to get the result. Only this time, the fake data will be returned and no network
            // traffic will leave your computer.
            return await GetCurrentWeather();
        }
    }
}
Clone this wiki locally