The .NET ecosystem has grown in versatility and performance over the years. In the latest versions of .NET, the introduction of Minimal APIs offers a streamlined way to build lightweight, high-performance HTTP APIs. These APIs allow developers to create fast and efficient web services with minimal boilerplate code, resulting in reduced complexity and faster development times.
In this blog post, we’ll explore what Minimal APIs are, why they’re useful, and how to get started with them using a simple example.
What Are Minimal APIs?
Minimal APIs in .NET are a new way to define HTTP routes and handle requests without the need for complex controller classes, attribute routing, or dependency injection setup. They provide a simple, straightforward approach to building APIs, and they were first introduced in .NET 6.
Before Minimal APIs, creating an API in ASP.NET Core typically required the following:
- Creating a
Controllerclass. - Defining methods in the controller.
- Using routing attributes (
[HttpGet],[HttpPost], etc.) to map HTTP requests to controller actions.
Minimal APIs remove the need for a controller class and route attributes, allowing you to define endpoints directly in the Program.cs file (or Startup.cs file for older versions). This leads to a more concise and performant codebase, which can be especially beneficial for microservices, small applications, or quick prototypes.
Benefits of Minimal APIs
- Reduced Boilerplate: Minimal APIs eliminate the need for controllers, model binding, and routing attributes. Everything is set up directly in the
Program.csfile. - Improved Performance: With fewer layers of abstraction, Minimal APIs tend to offer better performance, making them ideal for microservices or high-performance applications.
- Simplified Development: The concise syntax and lack of boilerplate make development faster and easier.
- Optimized for Cloud & Containers: Since they are lightweight, they are especially useful in containerized and cloud-native environments, where small, efficient services are paramount.
Building a Minimal API Example
Let’s go through a simple example to see how Minimal APIs are used in practice. We will build a basic “ToDo List” API, which allows users to view, create, and delete tasks.
1. Create a New .NET Web API Project
First, create a new .NET Web API project using the .NET CLI. Open your terminal or command prompt and run the following command:
dotnet new web -n MinimalApiExample
This command creates a new web application with the necessary boilerplate.
2. Define the ToDo Model
In the Models folder (create one if it doesn’t exist), define a simple ToDoItem class. This class will represent our task.
namespace MinimalApiExample.Models
{
public class ToDoItem
{
public int Id { get; set; }
public string Task { get; set; }
public bool IsComplete { get; set; }
}
}
3. Define the Minimal API Endpoints
In .NET 6 and later, we can define our endpoints in the Program.cs file. Let’s open Program.cs and configure the Minimal API.
Here’s how you would define the API endpoints:
using MinimalApiExample.Models;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var toDoItems = new List<ToDoItem>
{
new ToDoItem { Id = 1, Task = "Learn Minimal APIs", IsComplete = false },
new ToDoItem { Id = 2, Task = "Write a blog post", IsComplete = false }
};
// Get all ToDo items
app.MapGet("/todos", () => toDoItems);
// Get a specific ToDo item by ID
app.MapGet("/todos/{id}", (int id) => toDoItems.FirstOrDefault(todo => todo.Id == id) ?? Results.NotFound());
// Create a new ToDo item
app.MapPost("/todos", (ToDoItem newItem) =>
{
newItem.Id = toDoItems.Max(todo => todo.Id) + 1;
toDoItems.Add(newItem);
return Results.Created($"/todos/{newItem.Id}", newItem);
});
// Delete a ToDo item by ID
app.MapDelete("/todos/{id}", (int id) =>
{
var todo = toDoItems.FirstOrDefault(todo => todo.Id == id);
if (todo is null) return Results.NotFound();
toDoItems.Remove(todo);
return Results.NoContent();
});
app.Run();
4. Explanation of the Code
Break down what’s happening in the Program.cs file:
app.MapGet("/todos", ...): This endpoint returns all ToDo items.app.MapGet("/todos/{id}", ...): This endpoint retrieves a specific ToDo item by itsid.app.MapPost("/todos", ...): This endpoint creates a new ToDo item. It accepts aToDoItemobject from the request body, assigns a new ID, and adds it to the list.app.MapDelete("/todos/{id}", ...): This endpoint deletes a ToDo item by itsid.
Notice how the routes are defined directly in the Program.cs file, without the need for controllers or attributes.
5. Run the Application
Now, run your application using the following command:
dotnet run
Your API should now be up and running. You can test it by navigating to the following URLs in a browser or using a tool like Postman or curl:
GET http://localhost:5000/todos– Get all ToDo items.GET http://localhost:5000/todos/1– Get the ToDo item with ID 1.POST http://localhost:5000/todos– Create a new ToDo item (send JSON in the body).DELETE http://localhost:5000/todos/1– Delete the ToDo item with ID 1.
6. Testing the API
To test the POST request to create a new ToDo item, you can use Postman or curl. Here’s an example using curl:
curl -X POST "http://localhost:5000/todos" -H "Content-Type: application/json" -d "{\"Task\":\"Finish the blog post\",\"IsComplete\":false}"
This request will create a new ToDo item.
Conclusion
Minimal APIs in .NET are a powerful new feature for building lightweight, efficient APIs with minimal code. By eliminating the need for controllers and routing attributes, Minimal APIs allow developers to quickly define endpoints and handle requests in a concise, clear manner.