The world of web development is vast and ever-evolving, and mastering its many languages and frameworks is a rewarding journey. Among these, .NET is a robust and versatile platform that empowers developers to build high-quality, scalable, and secure applications. Today, we're going to delve into the exciting world of REST APIs and learn how to create and consume them using .NET.

REST (Representational State Transfer) APIs are the linchpin of modern web services, enabling communication between different software systems. They use standard HTTP methods (GET, POST, PUT, DELETE) and status codes to perform various operations. Let's get started by exploring how to create a simple REST API using ASP.NET Core, Microsoft's popular .NET framework for building web applications, IoT, and cloud-based solutions.

Setting Up Your First REST API with ASP.NET Core
To begin, let'screate a new ASP.NET Core Web API project. Open your terminal or command prompt and run the following command:

dotnet new webapi -n MyFirstApi
This command creates a new Web API project named 'MyFirstApi'. Navigate into the newly created directory with cd MyFirstApi, and you're ready to start coding.

Defining Your First Controller
A controller in ASP.NET Core is a class that handles HTTP requests and generates responses. Let's create a basic controller. In the 'Controllers' folder, add a new class called 'WeatherForecastController.cs':
public class WeatherForecastController : ControllerBase

Define a GET method in the controller to retrieve weather forecasts:
```
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Aggregate(new List<WeatherForecast>(), (weatherForecasts, i) =>
{
var forecast = new WeatherForecast
{
Date = DateTime.Now.AddDays(i),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
};
weatherForecasts.Add(forecast);
return weatherForecasts;
});
}
}
```
Now, you can run the application and access https://localhost:5001/weatherforecast to see the generated weather forecasts.

Creating Custom API Routes
By default, ASP.NET Core uses the controller name to determine the route. However, you can customize routes for better management and readability. To do this, modify the 'Startup.cs' file:









app.UseEndpoint Routing grossApp.Rutes.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
Replace the default route with a new one: app.UseRouting(); app.UseEndpoints(endpoints =>{endpoints.MapControllers();});
Now, create a new controller called 'AuthController.cs' and define a custom route for it:
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
You've now learned how to create REST APIs with custom routes in ASP.NET Core. In the next section, we'll explore consuming these APIs using .NET.
Consuming REST APIs in .NET
At times, you'll need to consume REST APIs in your .NET applications. The `HttpClient` class is the champion for making HTTP requests. Let's see how to use it to fetch data from our previously created 'WeatherForecastController'.
Using HttpClient to Make API Calls
First, install the `Newtonsoft.Json` NuGet package to serialize and deserialize JSON data. Then, create a new method in your controller to consume the API:
private async Task<List<WeatherForecast>> GetWeatherForecasts()
{
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://localhost:5001/weatherforecast");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<WeatherForecast>>
(stringResponse);
}
Now, you can consume the REST API created earlier and use the fetched data in your application.
Using HttpClient with Dependency Injection
Implementing dependency injection allows for better testability and maintainability. In your 'Startup.cs' file:
services.AddHttpClient();
In your controller, inject and use the `HttpClient` service:
private readonly HttpClient _httpClient;
public WeatherForecastController(HttpClient httpClient)
{
_httpClient = httpClient;
}
Now you can use the injected `_httpClient` to make API calls like before.
And that's a wrap! You're now well-equipped to create and consume REST APIs using .NET. Happy coding!