.NET Core Minimal API with Example

In this article, we will learn about the minimal API concept in .NET Core.

What is a Minimal API?

A Minimal API is a simplified approach to building APIs in .NET, introduced in .NET 6. It streamlines the process of creating HTTP services by reducing boilerplate code and configuration, making it easier to set up and maintain. This approach is particularly beneficial for microservices, small applications, or rapid prototyping.

Key Features of Minimal API

  1. Simplified Configuration: Minimal APIs reduce the amount of boilerplate code needed to set up an API.
  2. Top-Level Statements: Allows writing API code without the need for a Startup class or a Program class.
  3. Lightweight: Ideal for small, quick applications or microservices where a full MVC pattern might be overkill.
  4. Enhanced Performance: With fewer abstractions, minimal APIs can lead to better performance.

Creating a Minimal API in .NET Core

Here’s a step-by-step guide to creating a Minimal API in .NET Core

Step 1: Setting Up Your Project

First, create a new .NET Core project. You can use the .NET CLI to do this:

dotnet new web -o MinimalApiDemo
cd MinimalApiDemo

Step 2: Adding Minimal API Code

Open the Program.cs file and replace its content with the following code:

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

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

app.MapGet("/weather", () =>
{
    var weatherSummaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateTime.Now.AddDays(index),
            Random.Shared.Next(-20, 55),
            weatherSummaries[Random.Shared.Next(weatherSummaries.Length)]
        ))
        .ToArray();

    return forecast;
});

app.Run();

record WeatherForecast(DateTime Date, int TemperatureC, string Summary);

Step 3: Running the Application

Run the application using the following command:

dotnet run

The API will start, and you can test it by navigating to http://localhost:5000 in your browser or using a tool like curl or Postman.

Detailed Explanation

  1. WebApplication.CreateBuilder: Initializes the web application builder with default settings.
  2. builder.Build(): Builds the application.
  3. app.MapGet: Maps HTTP GET requests to the specified URL path. The first endpoint returns “Hello, World!” when accessing the root URL ("/").
  4. Weather Forecast Endpoint: A more complex endpoint that returns a list of weather forecasts. The forecasts are generated randomly for demonstration purposes.
  5. record WeatherForecast: Defines a record type for weather forecast data. Records are a concise way to create immutable objects with value-based equality.

POST Operation with Minimal API in .NET Core

The POST operation in a Minimal API is used to create new resources on the server. It typically involves accepting data from the client, processing it, and storing it in a database or other storage mechanisms.

Steps to Implement a POST Operation

  1. Set Up the Project: Ensure you have a minimum .NET 6 project set up.
  2. Define the Model: Create a model that represents the data structure.
  3. Implement the POST Endpoint: Define a POST endpoint that accepts data and processes it.

Sample Code for a POST Operation

Step 1: Setting Up the Project

Create a new .NET 6 or greater version project if you haven’t already:

dotnet new web -o MinimalApiPostDemo
cd MinimalApiPostDemo

Step 2: Define the Model

Create a model class to represent the data structure. For example, let’s create a TodoItem model:

// TodoItem.cs
public record TodoItem(int Id, string Title, bool IsCompleted);

Step 3: Implement the POST Endpoint

Modify the Program.cs file to include a POST endpoint:

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

var todoItems = new List<TodoItem>();

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

app.MapGet("/todos", () => todoItems);

app.MapPost("/todos", (TodoItem todoItem) =>
{
    todoItems.Add(todoItem);
    return Results.Created($"/todos/{todoItem.Id}", todoItem);
});

app.Run();

public record TodoItem(int Id, string Title, bool IsCompleted);

Explanation of the Code

  1. Setup: The WebApplication.CreateBuilder(args) initializes the web application builder with default settings, and builder.Build() builds the application.
  2. In-Memory List: An in-memory list (todoItems) is used to store TodoItem instances for demonstration purposes.
  3. GET Endpoints:
    • app.MapGet("/", () => "Hello, World!"): A simple endpoint to check if the API is running.
    • app.MapGet("/todos", () => todoItems): Returns the list of TodoItem instances.
  4. POST Endpoint:
    • app.MapPost("/todos", (TodoItem todoItem) => ...) maps POST requests to the /todos URL.
    • The todoItem parameter is automatically bound from the request body.
    • The new todoItem is added to the todoItems list.
    • Results.Created($"/todos/{todoItem.Id}", todoItem) returns a 201 Created response with the location of the newly created resource.

Running the Application

Run the application using the following command:

dotnet run

You can test the POST operation using a tool like curl or Postman. For example, with curl:

curl -X POST https://localhost:5001/todos -H "Content-Type: application/json" -d '{"id":1,"title":"Learn Minimal API","isCompleted":false}'

This command sends a POST request to the /todos endpoint with a JSON payload representing a TodoItem.

Benefits of Minimal APIs for POST Operations

  • Simplicity: Minimal setup and boilerplate code.
  • Ease of Use: Straightforward to define and map endpoints.
  • Performance: Less overhead compared to full MVC applications.
  • Flexibility: Suitable for various applications, from microservices to small APIs.

File Upload with Minimal API in .NET Core

If we want to handle file uploads as well, we can manage the code to include file processing with .NET Core minimal API.

Let’s see this in action:

app.MapPost("/upload", async (HttpRequest request) =>
{
    if (!request.HasFormContentType)
    {
        return Results.BadRequest("Form content type is required.");
    }

    var form = await request.ReadFormAsync();
    var formData = form["data"];
    var files = form.Files; // This will give you the collection of files

    foreach (var file in files)
    {
        // Process each file as needed
    }

    return Results.Ok(new { Message = "Form data and files received", Data = formData.ToString(), FileCount = files.Count });
});

Here, the code snippet will handle both form fields and file uploads, making the minimal API more versatile for various use cases.

Benefits of Using Minimal API in .NET Core

  • Reduced Complexity: Less boilerplate code means faster development and easier maintenance.
  • Performance: Fewer abstractions can lead to improved performance.
  • Flexibility: Suitable for a variety of applications, from microservices to small APIs.
  • Ease of Use: Simple and straightforward, making it accessible to developers of all skill levels.

Conclusion

Minimal APIs in .NET 6 offer a streamlined, efficient way to build HTTP services. They are particularly useful for small applications, microservices, or rapid prototyping, where the full power of ASP.NET Core MVC might not be necessary. With minimal configuration and a straightforward approach, developers can quickly create performant APIs.

Keep Following: SharePointCafe.NET

Leave a Comment

RSS
YouTube
YouTube
Instagram