Creating and Consuming REST APIs

API basics with ASP.NET Core and C# clients

Posted by Rodrigo Castro on December 28, 2024

REST APIs let applications communicate over HTTP. In .NET, you can both build APIs (servers) and consume them (clients).

🛠️ Creating a REST API (ASP.NET Core)

  1. Create a project:
    1
    2
    
    dotnet new webapi -n MyRestApi
    cd MyRestApi
    
  2. Add a sample controller:
    1
    2
    3
    4
    5
    6
    7
    
    [ApiController]
    [Route("[controller]")]
    public class ProductsController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<string> Get() => new[] { "Apple", "Banana" };
    }
    
  3. Test with Swagger:
    Run dotnet run and visit /swagger.

🌐 Consuming a REST API (C# client)

Use HttpClient to make HTTP requests:

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

var client = new HttpClient();
var response = await client.GetAsync("https://api.example.com/products");
var json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);

🔑 Tips

  • Use HttpClientFactory for better performance in production apps.
  • APIs often use JSON; you can deserialize using System.Text.Json.

Next: Using HttpClient in more detail!