Home About Skills Products Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Blog · .NET

Building Your First REST API with ASP.NET Core

Building Your First REST API with ASP.NET Core

ASP.NET Core's minimal API style (introduced in .NET 6, refined through .NET 10) strips away a lot of the ceremony older .NET developers remember from full MVC controllers. Here's the fastest real path to a working, production-reasonable API.

Creating the Project

dotnet new webapi -n MyApi -minimal
cd MyApi
dotnet run

Defining Endpoints

var app = WebApplication.Create(args);

app.MapGet("/posts", () => Results.Ok(posts));

app.MapGet("/posts/{id}", (int id) =>
{
    var post = posts.FirstOrDefault(p => p.Id == id);
    return post is not null ? Results.Ok(post) : Results.NotFound();
});

app.MapPost("/posts", (CreatePostDto dto) =>
{
    var post = new Post(posts.Count + 1, dto.Title, dto.Body);
    posts.Add(post);
    return Results.Created($"/posts/{post.Id}", post);
});

app.Run();

No controller classes, no attribute routing — just direct route-to-handler mappings, which is exactly what most CRUD endpoints actually need.

Entity Framework Core for the Database

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("Default")));
app.MapGet("/posts", async (AppDbContext db) =>
    await db.Posts.ToListAsync());

EF Core's DbContext is registered once and injected directly into route handlers — the same dependency injection pattern that runs through the entire .NET ecosystem.

Validation with FluentValidation

public class CreatePostValidator : AbstractValidator<CreatePostDto>
{
    public CreatePostValidator()
    {
        RuleFor(x => x.Title).NotEmpty().MaximumLength(255);
    }
}

Structuring as It Grows

Minimal APIs stay clean for small-to-medium services, but once you have dozens of endpoints, group related ones into extension methods (app.MapPostEndpoints()) rather than one giant Program.cs file. The underlying request pipeline, DI container, and middleware system are identical to full MVC — you're only opting out of controller classes, not out of ASP.NET Core's actual architecture.

ASP.NET Core Web API Authentication with JWT

ASP.NET Core Web API Authentication with JWT

A complete JWT authentication setup for ASP.NET Core — issuing tokens, protecting endpoints, and role-based authorization.

Entity Framework Core Migrations: A Practical Guide

Creating, applying, and safely rolling back EF Core migrations — the .NET equivalent of Laravel migrations, and where the workflow differs.

Clean Architecture in ASP.NET Core

Clean Architecture in ASP.NET Core

Structuring an ASP.NET Core app so business logic has zero dependency on frameworks or databases — Domain, Application, Infrastructure, and Web layers.

Esc