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:
- A Controller class inheriting from
ControllerBase. - Attribute routing (
[Route],[HttpGet]). - 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):
dotnet new web -o MinimalApiDemo
cd MinimalApiDemo
code .The Structure (Program.cs):
This is a fully functional web API in .NET 8/9:
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)
- GET (
MapGet): Retrieval of data. Should be safe and idempotent (calling it multiple times changes nothing). - POST (
MapPost): Creation of new resources. Not idempotent. - PUT (
MapPut): Full update or replacement of a resource. - DELETE (
MapDelete): Removal of a resource.
💻 Implementation
Here is how we map these verbs in Program.cs.
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
appobject 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}
// 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
// '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
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
TypedResultsoverResultsif 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
- Official Documentation: Minimal APIs overview - ASP.NET Core
- Routing: Routing in ASP.NET Core
- Return Types: How to create responses in Minimal APIs
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:
Get All Products: Create an endpoint to handle
GETrequests to/products. This endpoint should return all products from the list with a200 OKstatus. It must also support an optional boolean query parameterinStock. IfinStockistrue, the endpoint should only return products where theInStockproperty is true.Get Product by ID: Create an endpoint to handle
GETrequests to/products/{id}. Theidis an integer route parameter with a type constraint.- If a product with the matching
Idis found, return the product with a200 OKstatus. - If no product is found, return a
404 Not Foundresponse.
- If a product with the matching
Create a Product: Create an endpoint to handle
POSTrequests to/products. The handler should accept aProductobject from the request body.- Add the new product to the in-memory list.
- Return a
201 Createdresponse, including the URI of the newly created resource (e.g.,/products/{newId}).
Update a Product: Create an endpoint to handle
PUTrequests to/products/{id:int}. The handler should accept the integeridfrom the route and aProductobject from the request body.- Find the existing product by
id. If not found, return a404 Not Foundresponse. - If found, update its properties with the values from the request body and return a
204 No Contentresponse.
- Find the existing product by
Delete a Product: Create an endpoint to handle
DELETErequests to/products/{id:int}.- Find the product by the integer
idfrom the route. If not found, return a404 Not Foundresponse. - If found, remove it from the list and return a
204 No Contentresponse.
- Find the product by the integer
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.
A
MapGetendpoint for/products. The handler must accept an optionalbool?(nullable boolean) namedinStockfrom the query string. It should filter theproductslist based on this parameter if it has a value and return the result usingResults.Ok().A
MapGetendpoint for/products/{id:int}. The handler must accept anint idfrom the route. It should find the corresponding product. If found, it returns the product withResults.Ok(). If not, it returnsResults.NotFound().A
MapPostendpoint for/products. The handler must accept aProductobject. It should add this product to theproductslist and return aResults.Created()response, providing the location of the new resource (e.g.,/products/{product.Id}).A
MapPutendpoint for/products/{id:int}. The handler must accept anint idand aProduct inputProduct. It must find the product to update byid. If it doesn't exist, it returnsResults.NotFound(). Otherwise, it updates the existing product's details and returnsResults.NoContent().A
MapDeleteendpoint for/products/{id:int}. The handler must accept anint id. It must find the product byid. If it doesn't exist, it returnsResults.NotFound(). Otherwise, it removes the product from the list and returnsResults.NoContent().
All route handlers must return a type that implements IResult.