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)
- Create a project:
1 2
dotnet new webapi -n MyRestApi cd MyRestApi
- 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" }; }
- Test with Swagger:
Rundotnet 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!