Sending Requests and Handling Responses

HttpClient workflows in C#

Posted by Rodrigo Castro on January 10, 2025

When consuming APIs, you need to send requests and handle responses: including errors, status codes, and deserialization.

🚀 Sending Requests

1
2
var client = new HttpClient();
var response = await client.GetAsync("https://api.example.com/users/1");

📦 Handling Responses

  • Always check the status code:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();
        // Deserialize if needed
    }
    else
    {
        Console.WriteLine($"Error: {response.StatusCode}");
    }
    
  • Handle exceptions with try/catch.

🛠️ Deserializing JSON

1
2
3
using System.Text.Json;

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

🔄 POST/PUT Example

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

⚠️ Tips

  • Set necessary headers (like Authorization or User-Agent).
  • Use async/await for non-blocking I/O.

Next: Authentication and best practices for API integration!