Create a minimal API with ASP.NET Core

Introduction: In the world of web development, simplicity and efficiency are crucial factors when building high-performing applications. With the introduction of Minimal API in .NET 6, developers now have a lightweight and streamlined approach to creating HTTP services. In this blog post, we will explore the concept of Minimal API, discuss its benefits, and demonstrate how to create an HTTP service using Minimal API. Additionally, we’ll incorporate data fetching from an external API, implement logging for enhanced monitoring, and expose an endpoint for our HTTP service. Join us as we dive into the world of Minimal API and unlock its potential for building efficient and scalable web applications.

Table of Contents:

  • What is Minimal API?
  • Benefits of Minimal API
  • Setting up the Project
  • Fetching Data from an External API
  • Implementing Logging
  • Exposing an Endpoint for the HTTP Service
  • Conclusion

What is Minimal API?

Minimal API is a feature introduced in .NET 6 that simplifies the creation of HTTP services. It focuses on reducing boilerplate code and providing a clean and minimalistic syntax for defining routes and handling HTTP requests. With Minimal API, developers can build lightweight and efficient web applications with ease.

Benefits of Minimal API:

  • Reduced Ceremony: Minimal API eliminates excessive configuration and ceremony, allowing developers to focus on writing only the necessary code. This results in cleaner, more maintainable codebases.
  • Improved Performance: Minimal API has a smaller overhead compared to traditional approaches, leading to faster startup times and lower memory consumption. It is an ideal choice for resource-constrained environments.
  • Simplified Routing: Defining routes in Minimal API is straightforward, making it easier to handle different HTTP methods and route parameters without complex configuration.
  • Integrated Features: Minimal API seamlessly integrates with other ASP.NET Core features, such as dependency injection, middleware, and authentication, enabling developers to leverage the full power of the framework.

Setting up the Project:

To get started, ensure that you have .NET 6 installed on your machine. Open your preferred development environment and create a new Minimal API project using the following command:

dotnet new web -n MinimalApiDemo` 

Fetching Data from an External API:

In this section, we’ll demonstrate how to fetch data from an external API using Minimal API. Open the MinimalApiDemo.csproj file in the project folder and add the following package reference inside the <ItemGroup> element:

<ItemGroup>
  ...
  <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.0" />
  ...
</ItemGroup>

This package reference enables JSON serialization using Newtonsoft.Json, which we’ll use in our HTTP service.

Next, create a new file called DataController.cs in the project’s root directory and add the following code:

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;

[ApiController]
[Route("[controller]")]
public class DataController : ControllerBase
{
    private readonly HttpClient _httpClient;

    public DataController(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    [HttpGet]
    public async Task<IActionResult> GetData()
    {
        var response = await _httpClient.GetAsync("https://jsonplaceholder.typicode.com/posts");
        response.EnsureSuccessStatusCode();

        var content = await response.Content.ReadAsStringAsync();
        var data = JsonConvert.DeserializeObject(content);

        return Ok(data);
    }
}

In the above code, we define the DataController class, which represents our HTTP service. We inject an HttpClient instance through the constructor, which will be used to make HTTP requests. The GetData() action method retrieves data from an external API and returns it as an HTTP response.

Implementing Logging:

Logging is an essential aspect of any production-grade service. Minimal API makes it easy to incorporate logging using the built-in logging framework. To enable logging, modify the Program.cs file as follows:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);

// Configure logging
builder.Logging.ClearProviders();
builder.Logging.AddConsole();

// Register services
builder.Services.AddHttpClient();
builder.Services.AddLogging();

var app = builder.Build();

// Configure the app
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseLoggingMiddleware(); // Custom middleware for logging

app.MapGet("/", () => "Minimal API is up and running!");

app.MapControllers();

app.Run();

void UseLoggingMiddleware(IApplicationBuilder app)
{
    app.Use(async (context, next) =>
    {
        var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
        logger.LogInformation($"Request: {context.Request.Path}");
        await next.Invoke();
    });
}

In the code snippet above, we configure logging to use the console provider and add it to the builder. We also register the IHttpClientFactory and the logging service. Finally, we define custom middleware called UseLoggingMiddleware to log each incoming request.

Exposing an Endpoint for the HTTP Service:

To expose an endpoint for the HTTP service, we need to modify the Program.cs file further. Update the app.MapControllers() method as follows:

app.MapControllers();
app.MapGet("/data", () => app.RunControllerAction<DataController>(c => c.GetData()));

In this code snippet, we map the /data endpoint to the GetData() action method in the DataController class. Now, when you run the application and navigate to http://localhost:5000/data, you will receive the data fetched from the external API as the HTTP response.

Conclusion:

Minimal API is a powerful and efficient way to build HTTP services with minimal code and configuration. In this blog post, we explored the concept of Minimal API, discussed its benefits, and demonstrated how to create an HTTP service using Minimal API. We fetched data from an external API, implemented logging for enhanced monitoring capabilities, and exposed an endpoint for our HTTP service. By leveraging Minimal API, developers can create lightweight and high-performance services while maintaining a clean and maintainable codebase. Embrace the simplicity of Minimal API and unlock its potential for building efficient and scalable web applications.

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم