Minimal APIs in ASP.NET Core are a lightweight way to build HTTP APIs with minimal configuration and boilerplate code. They were introduced in .NET 6 as an alternative to the more complex MVC framework, providing a simpler and more concise way to create RESTful services.
Eang Sopheaktra
September 01 2024 05:04 pm
These instructions will get you to setup the project, install sdk and add package (CLI or Package manager console).
dotnet new webapi –-name MinimalAPIProject
Lightweight and Simple: Minimal APIs focus on reducing the overhead and boilerplate code associated with traditional MVC or Web API projects. You define endpoints directly in the Program.cs
file, making the structure of the application straightforward.
Top-Level Statements: You can define routes, handlers, and other middleware directly in the Program.cs
file using top-level statements, simplifying the overall structure.
No Controllers or Action Methods: Unlike the traditional MVC approach, Minimal APIs do not use controllers or action methods. Instead, you define endpoints as part of the application startup.
Flexibility and Performance: Minimal APIs offer high performance and are well-suited for microservices or lightweight applications. They provide a clear and concise way to define API endpoints without the overhead of MVC features that may not be necessary for simple services.
I created 'Endpoint' package for hand on all my minimal api endpoints. After that I created "StudentApiEndpoint".
using Microsoft.AspNetCore.Mvc;
using MinimalAPIProject.Dto.Request;
using MinimalAPIProject.Repository;
using MinimalAPIProject.Service;
namespace MinimalAPIProject.Endpoint;
public static class StudentApiEndpoint
{
public static IServiceCollection AddStudentApi(this IServiceCollection services)
{
services.AddSingleton(TimeProvider.System);
services.AddScoped<IStudentRepository, StudentRepository>();
services.AddScoped<IStudentService, StudentService>();
return services;
}
public static IEndpointRouteBuilder MapStudentApiRoutes(this IEndpointRouteBuilder builder)
{
var group = builder.MapGroup("/api/students");
{
// Get all Student items
_ = group.MapGet("", async ([FromServices] IStudentService studentService) =>
{
var results = await studentService.GetAllStudents();
return Results.Ok(results);
});
// Get a specific Student item
_ = group.MapGet("/{id}", async ([FromRoute] Guid id, [FromServices] IStudentService studentService) =>
{
var model = await studentService.GetStudentById(id);
return model is null ? Results.Problem("Item not found.", statusCode: StatusCodes.Status404NotFound) : Results.Json(model);
})
.Produces<string>(StatusCodes.Status200OK)
.ProducesProblem(StatusCodes.Status404NotFound);
// Create a new Student item
_ = group.MapPost("/", async ([FromBody] CreateStudentRequestDto createStudentRequestDto, [FromServices] IStudentService studentService) =>
{
var student = await studentService.CreateStudent(createStudentRequestDto);
return Results.Created($"/api/students/{student.Id}", student);
})
.Produces(StatusCodes.Status201Created)
.ProducesProblem(StatusCodes.Status400BadRequest);
// Mark a Student item as completed
_ = group.MapPut("/{id}", async ([FromRoute] Guid id, [FromBody] UpdateStudentRequestDto updateStudentRequestDto, [FromServices] IStudentService studentService) =>
{
bool? isUpdated = await studentService.UpdateStudent(id, updateStudentRequestDto);
return isUpdated switch
{
true => Results.NoContent(),
false => Results.Problem("Item already completed.", statusCode: StatusCodes.Status400BadRequest),
_ => Results.Problem("Item not found.", statusCode: StatusCodes.Status404NotFound),
};
})
.Produces(StatusCodes.Status204NoContent)
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status404NotFound);
// Delete a Student item
_ = group.MapDelete("/{id}", async ([FromRoute] Guid id, [FromServices] IStudentService studentService) =>
{
var wasDeleted = await studentService.DeleteStudent(id);
return wasDeleted ? Results.NoContent() : Results.Problem("Item not found.", statusCode: StatusCodes.Status404NotFound);
})
.Produces(StatusCodes.Status204NoContent)
.ProducesProblem(StatusCodes.Status404NotFound);
}
return builder;
}
}
AddStudentApi: using for add services and repositories
MapStudentApiRoutes: all group of endpoints of student
Yeeeeah good then also please update 'Program.cs'
Using for add student's services and repositories
//add services and repositories
builder.Services.AddStudentApi();
and add endpoint with this:
//all api's endpoints
app.MapStudentApiRoutes();
Minimal APIs in ASP.NET Core provide a simplified and efficient way to build APIs, especially when the full feature set of MVC is not needed. By reducing the amount of boilerplate code and offering direct configuration of routes and middleware, they enable developers to create RESTful services quickly and efficiently. Download the source code for the sample.