Consuming an API with HttpClient
Intermediate
20 min read
Lesson 6 of 10
The Phone Call Story: You have built a beautiful API, but how do you call someone else's API? You need a phone! In C#, your phone is the
HttpClient class. It allows your app to dial a URL, ask for data, and receive the response.
Connecting to C#
If you want to read a file on your computer, you use File.ReadAllText(). If you want to fetch data from the internet, you use HttpClient.
Example 1: Making a GET Request
using System.Net.Http;
using System.Threading.Tasks;
public class ApiConsumer
{
public async Task GetWeatherData()
{
// 1. Create the phone (HttpClient)
using HttpClient client = new HttpClient();
// 2. Dial the number (The API URL)
string url = "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41¤t_weather=true";
// 3. Make the call and wait for the answer
HttpResponseMessage response = await client.GetAsync(url);
// 4. Ensure the call was successful (Status 200)
response.EnsureSuccessStatusCode();
// 5. Read the JSON text answer
string jsonResponse = await response.Content.ReadAsStringAsync();
Console.WriteLine(jsonResponse);
}
}
Example 2: The Modern Way (Deserializing directly)
Instead of reading a raw string, you can immediately convert the JSON into a C# object using ReadFromJsonAsync.
// Inside an async method:
var weatherData = await client.GetFromJsonAsync<WeatherForecast>(url);
Console.WriteLine($"Current Temp: {weatherData.CurrentWeather.Temperature}");
Best Practice
Always use async and await when making network calls. Fetching data from the internet takes time, and async keeps your application responsive instead of freezing!