Exploring Minimal APIs in .NET 7: Advantages and Comparison with Traditional Web APIs

Exploring Minimal APIs in .NET 7: Advantages and Comparison with Traditional Web APIs

Introduction

.NET 6 introduced Minimal APIs, a powerful and efficient alternative to traditional web APIs in ASP.NET Core. As the .NET platform evolves with .NET 7, we can expect further enhancements and refinements to Minimal APIs, making them an increasingly appealing choice for building modern web applications. This article delves into Minimal APIs, discussing their advantages and suitable use cases. Additionally, we will compare Minimal APIs with traditional web APIs to help you make informed decisions about which approach best suits your needs.

A Closer Look at Minimal APIs

Minimal APIs are an innovative feature in ASP.NET Core designed to simplify web API creation by minimising the amount of boilerplate code required to set up an API. Developers can define HTTP endpoints using a concise and expressive C# syntax. With Minimal APIs, the focus is on the essential functionality of your API, while the framework handles common tasks such as routing, dependency injection, and middleware configuration.

New Features in .NET 7

.NET 7 brings several improvements and new features to Minimal APIs, making them nearly as powerful as traditional controllers. Some of the new features include:

  • Endpoint Filters: These allow you to validate parameters and body data sent in a request, log information about the request and response, and ensure that the request is being redirected to a valid API version.
  • Parameter Mapping: This feature allows you to map parameters in the URL to different types or names in your code, making it easier to work with various data formats and sources.
  • Request Delegate Factories: These enable you to create reusable middleware components that can be added to multiple endpoints, making it easier to add common functionality to your API, such as authentication or logging.

Performance Improvements in .NET 7

.NET 7 brings significant performance improvements to the ASP.NET Core platform, which also benefits Minimal APIs. One of the key enhancements is support for HTTP/2, a more efficient version of the HTTP protocol that allows for faster uploads and downloads. However, to avoid any single connection from using too much memory on the server, there is still a connection-level limit on how many bytes can be sent at a time. These performance improvements, combined with the streamlined syntax and reduced overhead of Minimal APIs, make them an attractive option for building high-performance web APIs.

Key Advantages of Minimal APIs

  • Streamlined Syntax: One of the most notable benefits of Minimal APIs is their clean and straightforward syntax, which reduces the amount of code needed to define API endpoints. This leads to code that is more readable, maintainable, and understandable.
  • Accelerated Development: By eliminating boilerplate code, Minimal APIs facilitate faster web API development, allowing you to focus on implementing the core business logic.
  • Enhanced Performance: Minimal APIs have a lower overhead compared to traditional MVC-based APIs, resulting in better performance and reduced resource consumption.
  • The performance improvements in .NET 7 further enhance the performance of Minimal APIs.
  • Lower Barrier to Entry: The simplified syntax and reduced complexity of Minimal APIs make it easier for developers new to .NET or web API development to learn and get started

Minimal API Examples

Below are some examples of Minimal APIs to help you understand their simplicity and ease of use.

Example 1: Basic "Hello World!" API

var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run();
        

Example 2: API with Route Parameters

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/users/{userId}/books/{bookId}", 
    (int userId, int bookId) => $"The user id is {userId} and book id is {bookId}");
app.Run();
        

Example 3: Fetching Data from a Database

app.MapGet("/books", async (BooksDB db) => await db.Books.ToListAsync());
        

Example 4: API with OpenAPI Specification Support

app.MapGet("/books", async (BooksDB db) => await db.Books.ToListAsync())
   .Produces<List<Book>>(StatusCodes.Status200OK)
   .WithName("GetAllBooks")
   .WithTags("Getters");
        

These examples demonstrate the power and simplicity of Minimal APIs in ASP.NET Core. You can use them to create fully functioning REST endpoints with minimal code and configuration, bypassing the need for traditional scaffolding and controllers.

Working with File Data in Minimal APIs

Starting from .NET 7, Minimal APIs support more advanced actions, such as file processing. This enhancement allows you to upload files to an API endpoint by simply adding an?IFormFile?parameter to the endpoint method. Here's an example of an endpoint that uploads a text file, with each line representing a new TODO item to be inserted:

app.MapPost("/todos/upload", (IFormFile file,
    [FromServices] ITodosRepository repository) =>
{
    using var reader = new StreamReader(file.OpenReadStream());

    while (reader.Peek() >= 0)
        repository.InsertTodo(reader.ReadLine() ?? string.Empty);

});
        

In this example, reading from the uploaded file is as simple as calling the?OpenReadStream?method on the?IFormFile?implementation. You can then check if any lines are remaining by calling the?Peek?method on the stream. If there are any lines, you can read the next line by calling the?ReadLine?method.

Binding the Request Body as a Stream or PipeReader

Minimal APIs allow you to bind the request body as a?Stream?or?PipeReader?for efficient processing and storage of data. This is useful when you need to store data in blob storage or enqueue data to a queue provider, such as Azure Queue storage or Azure Blob storage. Here's an example of how to bind the request body as a?ReadOnlyMemory<byte>?and deserialize it using?JsonSerializer:

using System.Text.Json;
using System.Threading.Channels;
namespace BackgroundQueueService;
class BackgroundQueue : BackgroundService
{
    private readonly Channel<ReadOnlyMemory<byte>> _queue;
    private readonly ILogger<BackgroundQueue> _logger;
    public BackgroundQueue(Channel<ReadOnlyMemory<byte>> queue,
                               ILogger<BackgroundQueue> logger)
    {
        _queue = queue;
        _logger = logger;
    }
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var dataStream in _queue.Reader.ReadAllAsync(stoppingToken))
        {
            try
            {
                var person = JsonSerializer.Deserialize<Person>(dataStream.Span)!;
                _logger.LogInformation($"{person.Name} is {person.Age} " +
                                       $"years and from {person.Country}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
        }
    }
}
class Person
{
    public string Name { get; set; } = String.Empty;
    public int Age { get; set; }
    public string Country { get; set; } = String.Empty;
}
        

Allowing Unauthenticated Users to Access an Endpoint

You can use the?[AllowAnonymous]?attribute to allow unauthenticated users to access specific endpoints. This attribute can be applied to an endpoint method or chained to an endpoint using the AllowAnonymous()?method. Here are two examples of how to allow unauthenticated access to an endpoint:

app.MapGet("/login", [AllowAnonymous] () => "This endpoint is for all roles.");
app.MapGet("/login2", () => "This endpoint also for all roles.")
   .AllowAnonymous();
        

Comparing Minimal APIs with Traditional Web APIs

When deciding between Minimal APIs and traditional Web APIs, you should consider the following factors:

  1. Simplicity: Minimal APIs are designed for simplicity and ease of use, making them a good choice for lightweight and streamlined API development. They are especially suitable for small projects or cases where you want to get up and running quickly.
  2. Performance: Minimal APIs have been found to perform slightly better than traditional APIs. In one comparison, the Minimal API was about 40% faster in returning a simple 200 response with a string. Additionally, the memory footprint for the Minimal API was roughly 15MB less.
  3. Advanced features: If your project requires more advanced features such as content negotiation, authentication, and authorization, it's better to use Web API instead of Minimal API.
  4. Controllers and Frameworks: Traditional Web API controllers offer benefits like external documentation exposed as Swagger/OpenAPI and hints at where to divide your application if you later want to switch to microservices. However, Minimal APIs support a style of implementation that avoids indirection and the inversion of control that comes with a framework like ASP.NET, making the implementation easier to follow and understand.


Conclusion

In conclusion, the choice between Minimal APIs and traditional Web APIs depends on your project requirements and desired trade-offs. Minimal APIs are great for lightweight, simple projects and offer slightly better performance, while traditional Web APIs are better for projects that require advanced features and more control over the API implementation.


#ASPNETCore #WebAPI #APIdevelopment #programming

要查看或添加评论,请登录

Paul Nichols的更多文章

社区洞察

其他会员也浏览了