How Asp.Net Core minimal API template is useful to kick start a project with code

Introduction

These daysMinimal APIs have become one of the most talked-about features, not only because it provide a streamlined, lightweight way to build HTTP APIs with .NET but also reduce the boilerplate code required to create web services. In this tutorial, I will dive deep into how to set up Minimal APIs, build a simple API, and handle requests efficiently with .NET 8.


Why Minimal APIs?

Before diving into the code, let’s quickly discuss why Minimal APIs are the future of web development with .NET:

  1. Less Boilerplate: Reduced complexity compared to traditional MVC/Web API patterns.
  2. Faster Development: Great for microservices and small applications where speed is critical.
  3. Clean and Simple: Code remains clear and concise, improving maintainability.



Setting Up Your .NET 8 Project

To get started, make sure you have the latest version of .NET 8 installed. If you haven't done so already, you can download it from the official Microsoft .NET site.

Once you have .NET 8 installed, create a new Minimal API project:

This will create a new web application with the default template.


Creating a Simple Minimal API

Now, let's create a simple API to manage a list of users. Here's how you can structure your Minimal API:

  1. Open Program.cs, and you’ll see that there’s a default configuration for routing and endpoints.
  2. Add a simple route to fetch users:



Explanation:

  1. MapGet("/users", ...): This creates a GET endpoint for /users.
  2. The result is returned as an anonymous object containing user data.

When you run this app, you can navigate to https://localhost:5001/users and see the list of users as a JSON response.


Adding More Routes

Now let’s add POST and DELETE routes to enhance the API. First, let’s add a POST route for adding new users.


Here, I:


  1. Accept a user object (using dynamic for simplicity).
  2. Add a new user to an in-memory list and return the created user with a 201 HTTP status code.

Adding a DELETE Endpoint

Now, let's implement the ability to delete a user:



Conclusion:

Minimal APIs in .NET simplify building lightweight, efficient APIs with fewer lines of code. In this quick tutorial, I have shown how easy it is to create routes, handle HTTP requests, and build simple endpoints with minimal configuration. Whether building microservices, APIs for small applications, or experimenting with new features in .NET 8, Minimal APIs offer a great foundation to kickstart your next project.


Next Steps:

This was all the basic introduction of a minimal API project and idea and I am almost thinking of extending this post to a series and in next posts I would like to cover:

  1. Adding database support with Entity Framework Core.
  2. Implementing authentication and authorization.
  3. Exploring middleware and other advanced features of Minimal APIs.