-
-
Notifications
You must be signed in to change notification settings - Fork 11
Sample Retrieving some Weather data from a 3rd party REST API
Pure Krome edited this page Apr 26, 2017
·
6 revisions
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.Net.Http;
using System.Threading.Tasks;
using WorldDomination.Net.Http;
namespace HttpClient.Helpers.SampleConsoleApplication
{
public class Program
{
private static Uri MebourneWeatherApiEndpoint = new Uri(
"http://api.openweathermap.org/data/2.5/weather?q=Melbourne,AU&APPID=e73e7e23d05a82823d68fbe5069766aa");
// CONSOLE APP - ENTRY POINT.
// This just calls the real & fake methods, to compare both ways.
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(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(fakeResult);
Console.WriteLine("");
Console.WriteLine("End of sample console application. Thank you for trying this out :)");
Console.WriteLine("");
}
// The main logic that _can_ call the real endpoint.
// If no fake response is provided, then it does a REAL call. Otherwise, just return
// the fake response.
private static async Task<string> GetCurrentWeather(HttpMessageHandler fakeHttpMessageHandler = null)
{
string content;
using (var httpClient = fakeHttpMessageHandler == null
? new System.Net.Http.HttpClient()
: new System.Net.Http.HttpClient(fakeHttpMessageHandler))
{
content = await httpClient.GetStringAsync(MebourneWeatherApiEndpoint);
}
return content;
}
// How to create the fake response :)
private static Task<string> GetFakeWeather()
{
// Set up the fake response for the Weather API Endpoint.
var messageResponse = FakeHttpMessageHandler.GetStringHttpResponseMessage("I am some fake weather result");
var options = new HttpMessageOptions
{
HttpResponseMessage = messageResponse,
RequestUri = MebourneWeatherApiEndpoint
};
var messageHandler = new FakeHttpMessageHandler(options);
// Now attempt to get the result. Only this time, the fake data will be returned and no network
// traffic will leave your computer.
return GetCurrentWeather(messageHandler);
}
}
}
- The Basics
- Common 'Happy Path' usages
- Common 'Sad Panda' usages
- Other interesting stuff