Using HttpClient for API Calls

Make HTTP requests in C#

Posted by Rodrigo Castro on December 29, 2024

HttpClient is the main way to call REST APIs from C#.

🚀 Basic Usage

1
2
3
4
5
6
7
using System.Net.Http;
using System.Threading.Tasks;

var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://api.github.com/zen");
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);

📝 POST Example

1
2
var payload = new StringContent("{\"name\":\"Alice\"}", Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.example.com/users", payload);

⚠️ Tips

  • Set headers as needed:
    1
    
    client.DefaultRequestHeaders.UserAgent.ParseAdd("MyApp/1.0");
    
  • For best practice, reuse HttpClient or use IHttpClientFactory in ASP.NET Core.

📦 Deserialize JSON

1
2
3
using System.Text.Json;

var user = JsonSerializer.Deserialize<User>(content);

Next: JSON serialization and deserialization in depth!