Weather.com API Integration: A Complete C# .NET Client Tutorial

Written by

in

Creating a custom Weather.com (The Weather Company / IBM) client using C# and .NET requires interacting with their RESTful API endpoints. Since Weather.com provides business-grade weather feeds, building a clean, modern, typed client wrapper ensures that your application manages API keys safely, leverages native asynchronous methods, and handles payloads cleanly using System.Text.Json.

Here is a comprehensive guide to structuring and coding a custom .NET client. 1. Structure the Response Models

The Weather Company APIs return structured JSON data. You must first create data transfer objects (DTOs) that accurately represent the incoming payload. Using JsonPropertyName ensures flexibility if your local C# property naming convention (PascalCase) differs from their JSON keys (camelCase).

using System.Text.Json.Serialization; namespace WeatherClient.Models; public record WeatherResponse( [property: JsonPropertyName(“location”)] Location Location, [property: JsonPropertyName(“current”)] CurrentCondition Current ); public record Location( [property: JsonPropertyName(“city”)] string City, [property: JsonPropertyName(“latitude”)] double Latitude, [property: JsonPropertyName(“longitude”)] double Longitude ); public record CurrentCondition( [property: JsonPropertyName(“temperature”)] double Temperature, [property: JsonPropertyName(“humidity”)] int Humidity, [property: JsonPropertyName(“uvIndex”)] int UvIndex, [property: JsonPropertyName(“phrase”)] string ConditionPhrase ); Use code with caution. 2. Design the Client Interface

Creating an interface allows you to mock the service later for unit testing.

using WeatherClient.Models; namespace WeatherClient.Services; public interface IWeatherClient { Task GetCurrentWeatherAsync(string locationQuery, string unit = “m”); } Use code with caution. 3. Implement the Typed HttpClient

Instead of instantiating HttpClient inside a using block—which can lead to socket exhaustion—you should create a Typed Client. This approach encapsulates the api.weather.com base configuration and injects the HTTP context smoothly via dependency injection.

using System.Net.Http.Json; using Microsoft.Extensions.Logging; using WeatherClient.Models; namespace WeatherClient.Services; public class CustomWeatherClient : IWeatherClient { private readonly HttpClient _httpClient; private readonly string _apiKey; private readonly ILogger _logger; public CustomWeatherClient(HttpClient httpClient, string apiKey, ILogger _logger) { _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _apiKey = !string.IsNullOrWhiteSpace(apiKey) ? apiKey : throw new ArgumentException(“API key cannot be empty.”); this._logger = _logger; } public async Task GetCurrentWeatherAsync(string locationQuery, string unit = “m”) { try { // Weather.com URLs usually require the query, unit format, and the API key string requestUri = $“v3/wx/conditions/current?apiKey={_apiKey}&geocode={locationQuery}&format=json&units={unit}”; HttpResponseMessage response = await _httpClient.GetAsync(requestUri); if (!response.IsSuccessStatusCode) { _logger.LogError(“Weather.com API returned an error: {StatusCode}”, response.StatusCode); response.EnsureSuccessStatusCode(); } return await response.Content.ReadFromJsonAsync(); } catch (HttpRequestException ex) { _logger.LogError(ex, “Transient error occurred while calling Weather.com API.”); throw; } catch (Exception ex) { _logger.LogError(ex, “An unexpected error occurred.”); return null; } } } Use code with caution. 4. Register the Client in your Application Container

In modern .NET applications (Program.cs), register the client with the built-in IHttpClientFactory container. This allows you to configure global parameters like timeouts, default headers, or resiliency policies.

using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using WeatherClient.Services; var builder = Host.CreateApplicationBuilder(args); // Grab your secure configuration keys string apiKey = builder.Configuration[“WeatherCom:ApiKey”] ?? “YOUR_DEFAULT_API_KEY”; // Register the custom typed client builder.Services.AddHttpClient(client => { client.BaseAddress = new Uri(”https://weather.com”); client.DefaultRequestHeaders.Add(“Accept”, “application/json”); client.Timeout = TimeSpan.FromSeconds(10); }); var host = builder.Build(); Use code with caution. 5. Best Practices Checklist

Transient Fault Handling: Weather APIs can experience momentary downtime or network drops. Use the Microsoft.Extensions.Http.Resilience package (built on Polly) to instantly configure retry rules and circuit breakers into your AddHttpClient registry.

Caching Mechanisms: To respect API rate limits and optimize speed, store retrieved weather data in memory (IMemoryCache) using a short expiration window (such as 10 to 15 minutes), since current ambient weather conditions do not fluctuate second by second.

Secure Key Vaults: Never hardcode API keys into C# files. Store them securely using user secrets during local development or utilize platforms like Azure Key Vault / Environment Variables in production. Medium·Mutlu Ozkurt

Creating an MCP Server and Client with .NET: A Step-by-Step Guide

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *