Building RESTful APIs with ASP.NET Core Minimal APIs

Introduction to Minimal APIs

Minimal APIs in ASP.NET Core represent a streamlined approach to building HTTP services. Introduced in .NET 6 and enhanced in subsequent versions, this architectural pattern enables developers to create lightweight, efficient web APIs with minimal boilerplate code. Unlike traditional MVC controllers, Minimal APIs use a functional style that allows you to define endpoints directly in your application's startup configuration.

These APIs are particularly well-suited for microservices, single-page applications (SPAs), and mobile backends where you need fast, responsive endpoints without the overhead of a full MVC framework. They inherently support JSON serialization, making them ideal for modern JavaScript frameworks and mobile applications.

Understanding HTTP APIs

HTTP APIs serve as communication bridges between different software systems, using standard web protocols to exchange data. Think of them as universal translators that enable diverse applications to understand each other's requests and responses.

Key characteristics of HTTP APIs include:

  • Protocol Adherence: They follow HTTP standards, using methods like GET for retrieval, POST for creation, PUT for updates, and DELETE for removal
  • Stateless Communication: Each request contains all necessary information, with servers maintaining no session state between requests
  • Resource-Oriented: Following REST principles, APIs expose resources that clients can manipulate through standard operations
  • Format Flexibility: Support for various data formats, with JSON being the predominant choice for modern applications

Creating Your First Minimal API

Let's create a simple Minimal API project to demonstrate the concepts:

Start by launching Visual Studio 2022 and creating a new project. Select the "ASP.NET Core Empty" template. Name your project something like "ProductCatalog" and configure it for .NET 8.0 with HTTPS enabled.

Once the project is created, replace the content of Program.cs with:

var serviceBuilder = WebApplication.CreateBuilder(args);
var application = serviceBuilder.Build();

// Configure a welcome endpoint
application.MapGet("/", () => "Welcome to Product Catalog API");

// Run the web server
application.Run();

Press Ctrl+F5 to launch the application without debugging. You'll see the welcome message in your browser when navigating to the root URL.

Expanding with Real-World Andpoints

Let's enhance our API with more practical endpoints. We'll create a simple product management system:

using Microsoft.AspNetCore.Mvc;

var serviceBuilder = WebApplication.CreateBuilder(args);
var application = serviceBuilder.Build();

// In-memory product storage (for demonstration)
var productDatabase = new List<Product>();
var productIdCounter = 1;

// Retrieve all products
application.MapGet("/api/products", () => {
    return Results.Ok(productDatabase);
});

// Retrieve a specific product by ID
application.MapGet("/api/products/{id:int}", (int id) => {
    var requestedProduct = productDatabase.FirstOrDefault(p => p.Id == id);
    return requestedProduct != null ? Results.Ok(requestedProduct) : Results.NotFound();
});

// Create a new product
application.MapPost("/api/products", (Product newProduct) => {
    newProduct.Id = productIdCounter++;
    productDatabase.Add(newProduct);
    return Results.Created($"/api/products/{newProduct.Id}", newProduct);
});

// Remove a product
application.MapDelete("/api/products/{id:int}", (int id) => {
    var productToRemove = productDatabase.FirstOrDefault(p => p.Id == id);
    if (productToRemove != null)
    {
        productDatabase.Remove(productToRemove);
        return Results.NoContent();
    }
    return Results.NotFound();
});

application.Run();

// Product entity definition
record Product(int Id, string Name, decimal Price, int StockQuantity);

This expanded example demonstrates key Minimal API features:

  • Multiple endpoint definitions with different HTTP verbs
  • Route parameters for dynamic values
  • Response types including Ok, NotFound, Created, and NoContent
  • Automatic JSON serialization for complex objects
  • Use of C# record types for immutable data structures

Advanced Features and Best Practices

Minimal APIs support dependency injection, allowing you to inject services into your endpoint handlers. Here's an example with a service class:

public interface IProductService
{
    IEnumerable<Product> GetAll();
    Product? GetById(int id);
    Product Create(Product product);
    bool Delete(int id);
}

public class ProductService : IProductService
{
    private readonly List<Product> _products = new();
    private int _nextId = 1;
    
    public IEnumerable<Product> GetAll() => _products;
    
    public Product? GetById(int id) => _products.FirstOrDefault(p => p.Id == id);
    
    public Product Create(Product product)
    {
        product = product with { Id = _nextId++ };
        _products.Add(product);
        return product;
    }
    
    public bool Delete(int id)
    {
        var product = _products.FirstOrDefault(p => p.Id == id);
        if (product == null) return false;
        
        _products.Remove(product);
        return true;
    }
}

// In Program.cs:
var serviceBuilder = WebApplication.CreateBuilder(args);
serviceBuilder.Services.AddSingleton<IProductService, ProductService>();

var application = serviceBuilder.Build();

application.MapGet("/api/products", (IProductService service) => service.GetAll());
application.MapGet("/api/products/{id}", (int id, IProductService service) => {
    var product = service.GetById(id);
    return product != null ? Results.Ok(product) : Results.NotFound();
});

application.Run();

Minimal APIs also support parameter binding, model validation, and custom middleware integration, making them powerful enough for production scenarios while maintaining their simplicity.

When to Chooce Minimal APIs

Consider using Minimal APIs for:

  • Microservice architectures where individual services need to be lightweight
  • Backend APIs for mobile applications
  • Simple CRUD operations and data endpoints
  • Prototyping and rapid development scenarios
  • Public-facing APIs with straightforward requirements

For complex applications requiring advanced routing, filters, or view rendering, traditional MVC controllers might still be the better choice.

Tags: ASP.NET Core Minimal APIs REST API .NET 8 Web APIs

Posted on Thu, 04 Jun 2026 19:09:27 +0000 by Sandip