Building APIs with Minimal APIs

6 min read

Welcome to the ASP.NET Core module. Today, we step away from the verbose traditions of the past and embrace the elegance of simplicity. We will explore Minimal APIs.

In this section, we focus on precision, performance, and code that speaks for itself.


1. Introduction to Minimal APIs: Fast, Clean, and Lightweight

Definition

Minimal APIs are a streamlined way to build HTTP APIs with ASP.NET Core using the absolute minimum dependencies and boilerplate code. They allow you to define endpoints directly in the Program.cs file using logical closures (lambdas), bypassing the traditional Controller-based architecture.

The Problem

Historically, building a Web API in .NET required a significant structural investment. To create a single endpoint returning "Hello World," a developer needed:

  1. A Controller class inheriting from ControllerBase.
  2. Attribute routing ([Route], [HttpGet]).
  3. Startup configuration to register controllers and map endpoints.

For simple microservices or rapid prototyping, this "ceremony" was excessive. It created a high cognitive load and file bloat for simple logic.

The Solution

Minimal APIs remove the ceremony. They leverage top-level statements (introduced in C# 9) and the WebApplication host to define logic where the application starts.

🧪 Industry Standard: Setting Up

To begin, we do not use the Model-View-Controller (MVC) template. We use the Empty web template.

Command Line Interface (CLI):

bash
dotnet new web -o MinimalApiDemo
cd MinimalApiDemo
code .

The Structure (Program.cs):
This is a fully functional web API in .NET 8/9:

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

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

app.Run();

Interesting Fact: When Minimal APIs were introduced in .NET 6, many long-time C# developers felt a sense of vertigo. We were so used to creating five folders before writing a line of logic that seeing a 4-line web server felt illegal. It wasn't. It was progress.


2. Routing Basics: Mapping HTTP Verbs

Definition

Routing is the mechanism that matches an incoming HTTP request (URL and Verb) to a specific executable delegate (code block).

The Problem

A web server receives thousands of requests. Without routing, the server has no way of distinguishing a request to get data from a request to delete data.

The Solution

The WebApplication object (app) exposes extension methods corresponding to standard HTTP verbs.

📜 The Vocabulary (HTTP Verbs)

  1. GET (MapGet): Retrieval of data. Should be safe and idempotent (calling it multiple times changes nothing).
  2. POST (MapPost): Creation of new resources. Not idempotent.
  3. PUT (MapPut): Full update or replacement of a resource.
  4. DELETE (MapDelete): Removal of a resource.

💻 Implementation

Here is how we map these verbs in Program.cs.

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

// 1. GET: Read data
app.MapGet("/items", () => 
{
    return new[] { "Notebook", "Pencil", "Eraser" };
});

// 2. POST: Create data
app.MapPost("/items", () => 
{
    // Logic to save item to database would go here
    return "Item created";
});

// 3. PUT: Update data
app.MapPut("/items", () => 
{
    return "Item updated";
});

// 4. DELETE: Remove data
app.MapDelete("/items", () => 
{
    return "Item deleted";
});

app.Run();

Imagination Check: Imagine the app object is a receptionist at a high-end hotel. The "Verb" is what the guest wants to do (Check-in, Room Service, Check-out), and the "Route" ("/items") is the room number. If the guest yells "POST" at room "/items", the receptionist knows exactly which procedure to run.


3. Extracting Data: Route Parameters and Query Strings

Definition

Data Binding is the process of extracting values from the HTTP request and mapping them to the parameters of your code handler.

The Problem

Static routes like /items are insufficient. We rarely operate on all items. We need to operate on specific items (e.g., Item #42) or filter lists (e.g., "all red items").

The Solution

We use Route Parameters for identification and Query Strings for modification/filtering.

A. Route Parameters

Used to identify a specific resource. Defined using curly braces {} in the route pattern.

Syntax: /users/{id}

csharp
// The framework automatically binds {id} from URL to the integer 'id'
app.MapGet("/users/{id}", (int id) => 
{
    return $"You requested User ID: {id}";
});

Request: GET /users/5
Response: "You requested User ID: 5"

B. Query Strings

Used for optional parameters, sorting, or filtering. These are not defined in the route pattern but are simply added as arguments to the lambda.

Syntax: /search?query=book

csharp
// 'q' is not in the route pattern "/"
// Therefore, ASP.NET Core looks for it in the Query String (?q=...)
app.MapGet("/search", (string q, int page = 1) => 
{
    return $"Searching for: {q} on page {page}";
});

Request: GET /search?q=minimal&page=2
Response: "Searching for: minimal on page 2"

Academic Note: Route constraints allow you to enforce data types directly in the URL structure. For example, /users/{id:int} ensures the endpoint only triggers if the ID is an integer. If a user visits /users/abc, the server returns a 404 (Not Found) automatically, sparing your code from crashing.


4. Communicating Back: Returning Responses and Status Codes

Definition

HTTP Responses consist of a Status Code (indicating success or failure) and a Payload (the data).

The Problem

Returning raw strings or objects (as seen in previous examples) defaults to a 200 OK status code. However, an API must be expressive.

  • If data isn't found, we must return 404.
  • If data is created, we should return 201.
  • If the user is wrong, we return 400.

The Solution

We use the Results static class or the IResult interface to control the response precisely.

💻 Implementation

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

var users = new List<string> { "Alice", "Bob", "Charlie" };

app.MapGet("/users/{id}", (int id) => 
{
    // Validation: Does the user exist?
    if (id < 0 || id >= users.Count)
    {
        // Return 404 Not Found
        return Results.NotFound(new { Message = "User not found" });
    }

    // Return 200 OK with data
    return Results.Ok(new { User = users[id] });
});

app.MapPost("/users", (string name) => 
{
    users.Add(name);
    
    // Return 201 Created
    // Ideally, we provide a link to the new resource, but here we just confirm creation.
    return Results.Created($"/users/{users.Count - 1}", name);
});

app.Run();

Common Results Methods

Method Status Code Usage
Results.Ok(data) 200 Standard success.
Results.Created(uri, data) 201 Resource successfully created.
Results.BadRequest(error) 400 Client sent invalid data.
Results.NotFound() 404 Resource does not exist.
Results.NoContent() 204 Success, but nothing to return (common for DELETE).

Best Practice: In .NET 7+, prefer using TypedResults over Results if you are planning to generate OpenAPI (Swagger) documentation. It helps the documentation generator understand exactly what your API returns without extra annotations.


📚 Further Reading & References

Challenge

You are tasked with building a minimal API for managing a product inventory. Using the provided Product record and initial products list, implement the following endpoints:

  1. Get All Products: Create an endpoint to handle GET requests to /products. This endpoint should return all products from the list with a 200 OK status. It must also support an optional boolean query parameter inStock. If inStock is true, the endpoint should only return products where the InStock property is true.

  2. Get Product by ID: Create an endpoint to handle GET requests to /products/{id}. The id is an integer route parameter with a type constraint.

    • If a product with the matching Id is found, return the product with a 200 OK status.
    • If no product is found, return a 404 Not Found response.
  3. Create a Product: Create an endpoint to handle POST requests to /products. The handler should accept a Product object from the request body.

    • Add the new product to the in-memory list.
    • Return a 201 Created response, including the URI of the newly created resource (e.g., /products/{newId}).
  4. Update a Product: Create an endpoint to handle PUT requests to /products/{id:int}. The handler should accept the integer id from the route and a Product object from the request body.

    • Find the existing product by id. If not found, return a 404 Not Found response.
    • If found, update its properties with the values from the request body and return a 204 No Content response.
  5. Delete a Product: Create an endpoint to handle DELETE requests to /products/{id:int}.

    • Find the product by the integer id from the route. If not found, return a 404 Not Found response.
    • If found, remove it from the list and return a 204 No Content response.

Expected result

The solution must contain a complete C# Minimal API implementation. The code must define the following five endpoints mapped to the app instance using the MapGet, MapPost, MapPut, and MapDelete methods.

  1. A MapGet endpoint for /products. The handler must accept an optional bool? (nullable boolean) named inStock from the query string. It should filter the products list based on this parameter if it has a value and return the result using Results.Ok().

  2. A MapGet endpoint for /products/{id:int}. The handler must accept an int id from the route. It should find the corresponding product. If found, it returns the product with Results.Ok(). If not, it returns Results.NotFound().

  3. A MapPost endpoint for /products. The handler must accept a Product object. It should add this product to the products list and return a Results.Created() response, providing the location of the new resource (e.g., /products/{product.Id}).

  4. A MapPut endpoint for /products/{id:int}. The handler must accept an int id and a Product inputProduct. It must find the product to update by id. If it doesn't exist, it returns Results.NotFound(). Otherwise, it updates the existing product's details and returns Results.NoContent().

  5. A MapDelete endpoint for /products/{id:int}. The handler must accept an int id. It must find the product by id. If it doesn't exist, it returns Results.NotFound(). Otherwise, it removes the product from the list and returns Results.NoContent().

All route handlers must return a type that implements IResult.

csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.