#csharp #dotnet #backend

Day 12: Building Your First Minimal API

Welcome to Day 12. We are going to build actual web endpoints using Minimal APIs.

Minimal APIs were introduced in .NET 6 to drastically reduce the boilerplate needed to create HTTP APIs. Instead of defining large classes and routing attributes, you map routes directly to delegates (lambdas) in Program.cs.

Setting up typical HTTP Verbs

The app object provides mapping methods for all standard REST verbs: MapGet, MapPost, MapPut, and MapDelete.

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

// Dummy in-memory list
var users = new List<string> { "Alice", "Bob" };

// GET Request (Read)
app.MapGet("/users", () => 
{
    return users; // Automatically serialized as JSON!
});

// POST Request (Create)
// When a JSON body is sent, the framework automatically deserializes it into the 'newUser' string.
app.MapPost("/users", (string newUser) => 
{
    users.Add(newUser);
    return Results.Created($"/users/{newUser}", newUser);
});

// DELETE Request
app.MapDelete("/users", () => 
{
    users.Clear();
    return Results.NoContent();
});

app.Run();

Why JSON is easy

Notice in the MapGet we just returned a C# List<string>. ASP.NET Core has a built-in JSON Serializer (System.Text.Json).

When your lambda returns an object, the framework automatically sets the HTTP Headers (Content-Type: application/json) and converts your C# classes/lists cleanly into JSON strings.

Async Endpoints

If your endpoint needs to talk to a database or make an external request, you just mark the lambda as async!

app.MapGet("/slow-data", async () => 
{
    await Task.Delay(2000); // Simulate DB read
    return new { Message = "Finally done!" }; // Returning an anonymous object
});

Testing your endpoints

Instead of building a frontend immediately, backend developers use tools to immediately fire HTTP requests at their servers:

  1. Swagger/OpenAPI (Usually built-in via the <PackageReference Include="Swashbuckle.AspNetCore" /> library)
  2. Postman / Insomnia (Desktop GUI tools)
  3. VS Code REST Client / Thunder Client extensions.

Challenge for Day 12

Create a Product class (Id, Name, Price). Create a static List<Product> in memory. Write a GET endpoint that returns all products, and a POST endpoint that accepts a purely new Product JSON object and adds it to the list.

Tomorrow: Parsing Route Parameters!