Building Minimal APIs with CRUD and Carter

Introduction

In the world of web development, APIs are increasingly becoming the backbone of modern web applications. They allow applications to communicate and exchange data with each other seamlessly. Minimal APIs, in particular, have gained popularity due to their simplicity and ease of use.

Minimal APIs are lightweight APIs that allow developers to create simple and efficient endpoints for their applications. They are built on top of the .NET 6 framework and provide a streamlined approach to building APIs.

In this article, we will discuss how to build minimal APIs with CRUD (Create, Read, Update, Delete) operations using Carter, a library for ASP.NET Core.

Building Minimal APIs with CRUD

Minimal APIs provide a simple and efficient way to create RESTful endpoints for your applications. The CRUD operations are the basic building blocks for any API. They allow you to create, read, update, and delete data from your application.

To create a minimal API with CRUD operations, you can use the following code, according to Microsoft documentation (https://learn.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-7.0&tabs=visual-studio-code):

var basketballPlayers = app.MapGroup("/BasketballPlayers");

basketballPlayers.MapGet("/BasketballPlayers", async (BasketPlayersTeamsDb db) =>
    await db.Players.ToListAsync());


basketballPlayers.MapGet("/BasketballPlayer/{id}", async (int id, BasketPlayersTeamsDb db) =>
    await db.Players.FindAsync(id)
        is BasketballPlayer player
            ? Results.Ok(player)
            : Results.NotFound());

basketballPlayers.MapPost("/BasketballPlayer", async (BasketballPlayer player, BasketPlayersTeamsDb db) =>
{
    db.Players.Add(player);
    await db.SaveChangesAsync();

    return Results.Created($"/BasketballPlayer/{player.Id}", player);
});

basketballPlayers.MapPut("/BasketballPlayeritems/{id}", async (int id, BasketballPlayer inputBasketballPlayer, BasketPlayersTeamsDb db) =>
{
    var BasketballPlayer = await db.Players.FindAsync(id);

    if (BasketballPlayer is null) return Results.NotFound();

    BasketballPlayer.Name = inputBasketballPlayer.Name;
    BasketballPlayer.Position = inputBasketballPlayer.Position;

    await db.SaveChangesAsync();

    return Results.NoContent();
});

basketballPlayers.MapDelete("/BasketballPlayer/{id}", async (int id, BasketPlayersTeamsDb db) =>
{
    if (await db.Players.FindAsync(id) is BasketballPlayer BasketballPlayer)
    {
        db.Players.Remove(BasketballPlayer);
        await db.SaveChangesAsync();
        return Results.Ok(BasketballPlayer);
    }

    return Results.NotFound();
});

This code creates a minimal API with endpoints for retrieving all BasketballPlayers, retrieving an BasketballPlayer by ID, creating a new item, updating an existing BasketballPlayers, and deleting an BasketballPlayers.

Here’s a simple example, but your program.cs file could quickly become huge when adding endpoints to meet the needs of your application.

Using Carter for Minimal APIs

Carter is an open-source library that provides a lightweight framework for building web APIs with ASP.NET Core. It is designed to be simple and easy to use, making it an excellent choice for building minimal APIs.

So you can group your endpoint on several modules in your presentation layer.

To use Carter for building minimal APIs, you can use the following code:

using Carter;
using Models;
using DbContexts;
using Microsoft.EntityFrameworkCore;

namespace Modules;


public class BasketballPlayerModule : CarterModule
{
    public override void AddRoutes(IEndpointRouteBuilder app)
    {
        var basketballPlayers = app.MapGroup("/BasketballPlayers");

        basketballPlayers.MapGet("/BasketballPlayers", async (BasketPlayersTeamsDb db) =>
            await db.Players.ToListAsync());


        basketballPlayers.MapGet("/BasketballPlayer/{id}", async (int id, BasketPlayersTeamsDb db) =>
            await db.Players.FindAsync(id)
                is BasketballPlayer player
                    ? Results.Ok(player)
                    : Results.NotFound());

        basketballPlayers.MapPost("/BasketballPlayer", async (BasketballPlayer player, BasketPlayersTeamsDb db) =>
        {
            db.Players.Add(player);
            await db.SaveChangesAsync();

            return Results.Created($"/BasketballPlayer/{player.Id}", player);
        });

        basketballPlayers.MapPut("/BasketballPlayeritems/{id}", async (int id, BasketballPlayer inputBasketballPlayer, BasketPlayersTeamsDb db) =>
        {
            var BasketballPlayer = await db.Players.FindAsync(id);

            if (BasketballPlayer is null) return Results.NotFound();

            BasketballPlayer.Name = inputBasketballPlayer.Name;
            BasketballPlayer.Position = inputBasketballPlayer.Position;

            await db.SaveChangesAsync();

            return Results.NoContent();
        });

        basketballPlayers.MapDelete("/BasketballPlayer/{id}", async (int id, BasketPlayersTeamsDb db) =>
        {
            if (await db.Players.FindAsync(id) is BasketballPlayer BasketballPlayer)
            {
                db.Players.Remove(BasketballPlayer);
                await db.SaveChangesAsync();
                return Results.Ok(BasketballPlayer);
            }

            return Results.NotFound();
        });

    }
}

And in this way, we can maintain a proper program.cs file:


using Microsoft.EntityFrameworkCore;
using DbContexts;
using Carter;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<BasketPlayersTeamsDb>(opt => opt.UseInMemoryDatabase("BasketballPlayerList"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCarter();

var app = builder.Build();
app.MapCarter();
app.UseSwagger();
app.UseSwaggerUI();
app.Run();

Conclusion

In conclusion, minimal APIs provide a lightweight and efficient way to build RESTful endpoints for your applications. By using the CRUD operations with Carter, you can create a simple and easy-to-use API for your application, and maintain a proper architecture in your application.

Carter provides a streamlined approach to building web APIs with ASP.NET Core. It allows you to create minimal APIs with ease and simplicity, making it an excellent choice for building modern web applications.

Find the full code on github : https://github.com/FiftyCloud/basketballplayer

Reference

https://learn.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-7.0&tabs=visual-studio-code

https://github.com/CarterCommunity?WT.mc_id=-blog-scottha

Une réponse à “Building Minimal APIs with CRUD and Carter”

  1. […] Minimal APIs are a new feature introduced in ASP.NET Core 6.0. They allow you to create endpoints with a minimal amount of code. You can create an endpoint with just a few lines of code, without needing to set up a full MVC application. This makes it easier and faster to create simple APIs.You can keep it proper with library like Carter as explain in my previous article : https://www.code-review.tech/building-minimal-apis-with-crud-and-carter/ […]

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *