Minimal APIs with Carter in .NET 8.0

Introduction

Carter is a library for building HTTP APIs in .NET. It simplifies the process of defining and organizing endpoints in your application. Here's a step-by-step guide on how to use Carter with Minimal API

The source code can be downloaded from GitHub

Create a minimal API Project in .NET 8.0

Start by creating a new minimal API project using the ‘dotnet new’ command.

dotnet new web -n MinimalAPIWithCarter

Install the Carter nuget package

You need to add the Carter Nuget package to the project. Open the package terminal and install it.

dotnet add package Carter

Define your endpoint with Carter

Open your “Pragram.cs” file and modify it to use Cartner. Remove the existing code and replace it with the following.

using Carter;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


builder.Services.AddCarter();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.MapCarter();

app.Run();

This sets up the basic structure of our Minimal API project, integrating Carter seamlessly.

Create Carter Module

In Carter, endpoints are organized using modules. Let's create a Modules folder in our project and add a sample module. For instance, create a file named SampleModule.cs with the following content:

using Carter;

namespace MinimalAPIWithCarter.Modules
{
    public class SampleModule : CarterModule
    {
        public override void AddRoutes(IEndpointRouteBuilder app)
        {

            app.MapGet("/hello", () =>
            {
                return "Hello, World!";
                
            });

        }
    }
}

Run Your minimal API

Run your application. You will get the below response over swagger.

Carter

Now you have a basic setup using Carter with .NET 8.0 Minimal API. You can continue adding more modules and endpoints as needed. Carter's documentation provides additional features and configurations you can explore