Skip to content

Instantly share code, notes, and snippets.

@PadreSVK
Created December 14, 2019 21:51
Show Gist options
  • Save PadreSVK/330e35b96515bdb43019602c0e8d8a18 to your computer and use it in GitHub Desktop.
Save PadreSVK/330e35b96515bdb43019602c0e8d8a18 to your computer and use it in GitHub Desktop.
Http client for OpenWeatherAPI
using System.Threading.Tasks;
using BackgroundServices.Models;
using BackgroundServices.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace BackgroundServices.HttpClients
{
public interface IOpenWeatherClient
{
Task<OpenWeatherRoot> GetDataByCity(string city);
}
public class OpenWeatherClient : IOpenWeatherClient
{
private readonly HttpClient httpClient;
private readonly IOptionsMonitor<OpenWeatherHttpClientOptions> openWeatherClientOptions;
private readonly ILogger<OpenWeatherClient> logger;
public OpenWeatherClient(HttpClient httpClient,
IOptionsMonitor<OpenWeatherHttpClientOptions> openWeatherClientOptions,
ILogger<OpenWeatherClient> logger)
{
this.httpClient = httpClient;
this.openWeatherClientOptions = openWeatherClientOptions;
this.logger = logger;
}
public async Task<OpenWeatherRoot> GetDataByCity(string city)
{
try
{
var response = await httpClient.GetAsync($"weather?APPID={openWeatherClientOptions.CurrentValue.Key}&q={city}&units=metric");
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<OpenWeatherRoot>(responseData);
return data;
}
logger.LogError($"Invalid request - {city}; {response.StatusCode}");
}
catch (Exception ex)
{
logger.LogError($"Request for - {city}", ex);
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment