Getting Started with Minimal API in .NET 7

Minimal API in .NET is a powerful tool for building simple and lightweight web APIs. It streamlines the development process by allowing developers to create APIs with minimal boilerplate code. In this post, we'll walk you through the steps of getting started with Minimal API in .NET, including its most basic features and setup steps.

Prerequisites

  • .NET 6 SDK (or higher) - we'll use .NET 7
  • Visual Studio 2022 or Visual Studio Code

Getting Started

To create a new Minimal API project, run the following command in your terminal or command prompt:
$ dotnet new web -n ProjectName -minimal
Alternatively you can use Visual Studio and create a new project using "ASP.NET Core Web API" template.
Make sure to untick the 'Use controllers' checkbox:
Once the project is created, navigate to the Program.cs file and override the content with following code:
var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

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

app.Run();
This code creates a new instance of the WebApplication class, adds a single endpoint to the API, and runs the application. It's the most basic use of the Minimal API.

To run the application, use either Visual Studio or use the following command in the terminal.
$ dotnet run
Your API is now running and ready for testing.

Routing

Map Methods

To add more endpoints, you can use the MapGet, MapPost, MapPut and MapDelete methods of the WebApplication class. Each of these methods takes two parameters - the endpoint URL and an async delegate that defines the endpoint handler. Here are few examples:
  • MapGet: handles HTTP GET requests
app.MapGet("/hello", () => "Hello, world!");
  • MapPost: handles HTTP POST requests
app.MapPost("/submit", async (HttpContext context) =>
{
    // handle the POST request
});
  • MapPut: handles HTTP PUT requests
app.MapPut("/update/{id}", async (int id, HttpContext context) =>
{
    // handle the PUT request with the given id
});
app.MapDelete("/delete/{id}", async (int id, HttpContext context) =>
{
    // handle the DELETE request with the given id
});

Additionally you can use MapMethods method. MapMethods is a routing method that allows you to define an endpoint that can handle multiple HTTP methods. This method takes three parameters - the endpoint URL, a list of HTTP methods that the endpoint should handle and an async delegate that defines the endpoint handler.
app.MapMethods("/hello", new[] { HttpMethods.Get, HttpMethods.Post }, async (HttpContext context) =>
{
    if (context.Request.Method == HttpMethods.Get)
    {
        return "Hello, world!";
    }
    else if (context.Request.Method == HttpMethods.Post)
    {
        // handle the POST request
    }
});

The extension method MapGroup is useful for organizing groups of endpoints that share a common prefix. It helps eliminate redundant code and allows customization of entire groups of endpoints. In the example below authorization is applied to all endpoints a group called projectGroup.
var projectGroup = app.MapGroup("/projects")
    .RequireAuthorization();

projectGroup.MapGet("/{projectId}", GetProject);

projectGroup.MapDelete("{projectId}", DeleteProject);

Handlers

A handler is a function that processes incoming HTTP requests and generates HTTP responses. Handlers are used to implement the logic of an endpoint in a modular and reusable way.

To use a handler in a Minimal API, you can define Lambda Expression as in the examples above:
app.MapPost("/submit", async () =>
{
    // handle the POST request
});

Another way is to pass a method as parameter:
private string GetHandler() => "This is a Get handler";

app.MapGet("/", GetHandler);
More handler examples you can find here.

Parameters Binding

Parameter binding in Minimal API is a technique for extracting request data and converting it into strongly typed parameters defined in the route handler. Below, we will provide some basic examples for different types of binding sources.
Supported binding sources:
  • Route path parameters
  • Route query string
  • Body in JSON format
  • Header values
  • Services from dependency injection container
  • Custom
Basic parameter binding:
app.MapGet("/greet/{name}", (string name) => $"Hello, {name}!");
Header values binding:
app.MapGet("/user/{id}", (int id, [FromHeader(Name = "Authorization")] string authorizationHeader) => { });
In the above example, header parameter is explicitly declared using "From" parameter. More about explicit parameter binding can be found here.

Services binding from DI container:
app.MapGet("/user/{id}", (int id, [FromServices] Service service) => { });
You can find more about parameters biding in Minimal API here.

What's next?

In our upcoming posts, we will cover more features of Minimal API and its use cases. Additionally, you can learn more about Minimal API from Microsoft's official documentation.

0 comments:

Post a Comment