Create a minimal API with ASP.NET Core

By FoxLearn 1/10/2025 7:10:20 AM   35
Ever wished you could skip all the boilerplate code that comes with controllers in your Web API?

Are you all about efficiency and want to directly return data from your repositories? Well, .NET 6.0 introduces the Minimal API feature, which allows you to build APIs without controllers keeping your codebase lean and easy to maintain.

Minimal APIs are designed to build HTTP APIs with minimal dependencies, making them perfect for microservices and applications that require a lightweight setup with only essential files, features, and dependencies in ASP.NET Core.

Create an ASP.NET Core Web API

To create an API project:

  • Open Visual Studio 2022 and select Create a new project.
  • In the "Create a new project" dialog, search for and select the ASP.NET Core Empty template, then click Next.
  • Name the project SimpleApi and click Next.
  • In the "Additional information" dialog, choose .NET 9.0, uncheck Do not use top-level statements, and click Create.

The Program.cs file contains the following code:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

Set Up a Simple Repository

In this example, we’ll create a mock repository that returns a string.

namespace SimpleApi.Repositories
{
    public class MyRepository
    {
        public async Task<string> GreetAsync()
        {
            // This is a simple mock example, but in practice, 
            // you'd have a real async operation here.
            return await Task.Run(() => "Greetings, Earth!");
        }

        public string Greet()
        {
            // A simple non-async method, showing that async is not always required.
            // Though async is recommended for I/O-bound operations.
            return "Greetings, Earth!";
        }

        public async Task<string> GreetPersonAsync(string name)
        {
            // A simple async method with a parameter, demonstrating parameter usage.
            return await Task.Run(() => $"Greetings, {name}!");
        }
    }
}

Add EndPoints to Program.cs

using SimpleApi.Repositories;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Register the repository to the DI container.
builder.Services.AddSingleton<MyRepository>(new MyRepository());

// Build the app.
var app = builder.Build();

// Add Swagger UI for development environments.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// Enforce HTTPS redirection.
app.UseHttpsRedirection();

// Create the first endpoint: A synchronous example.
app.MapGet("/api/greet", (MyRepository myRepo) => myRepo.Greet()).WithName("Greet Without Async");

// Create the second endpoint: An asynchronous example.
app.MapGet("/api/greet-async", async (MyRepository myRepo) => await myRepo.GreetAsync()).WithName("Greet With Async");

// Create the third endpoint: An asynchronous example with a parameter.
app.MapGet("/api/greet/{name}", async (string name, MyRepository myRepo) => await myRepo.GreetPersonAsync(name)).WithName("Greet Person With Async");

// Run the API.
app.Run();

By structuring your code like this, you demonstrate how to expose API endpoints for various scenarios, both with and without async operations.