ASP.Net Core 8 with Minimal API

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.

Sopheaktra

Eang Sopheaktra

September 01 2024 05:04 pm

0 265

Key Functions

  1. Student's API
  2. Swagger for API's Endpoint

Getting Started

These instructions will get you to setup the project, install sdk and add package (CLI or Package manager console).

Prerequisites

  • Visual Studio 2022 or higher
  • .NET 8.x SDK

Installing

  1. Install .net SDK 8
    Download .NET SDK here.
  2. Create new Web API's project (Please create main project with empty and add below to the main project)
dotnet new webapi –-name MinimalAPIProject

Languages and Tools

dotnet core  csharp 

Key Features of Minimal APIs:

  • 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.

When to Use Minimal APIs:

  • Microservices: Ideal for small, focused microservices where a full MVC setup would be overkill.
  • Prototyping: Great for quickly spinning up a simple API for proof of concept or prototype.
  • Serverless Applications: Minimal APIs are a good fit for serverless applications due to their lightweight nature.

Let start to example:

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();

Summary

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.

 

Comments

Subscribe to our newsletter.

Get updates about new articles, contents, coding tips and tricks.

Weekly articles
Always new release articles every week or weekly released.
No spam
No marketing, share and spam you different notification.
© 2023-2025 Tra21, Inc. All rights reserved.