DEV Community

Cover image for 🧱 Building a Todo List API with .NET Core Minimal APIs πŸš€ A Simple & Powerful Guide
YASH MAISURIYA
YASH MAISURIYA

Posted on

4 1 1 1 2

🧱 Building a Todo List API with .NET Core Minimal APIs πŸš€ A Simple & Powerful Guide

πŸš€ .NET Core's Minimal APIs offer a streamlined approach to building HTTP APIs with reduced boilerplate. This post walks you through creating a Todo list API from scratch, showcasing the simplicity and power of Minimal APIs.

Prerequisites

  • .NET Core SDK (latest version recommended)
  • A code editor (VS Code, JetBrains Rider, etc.)
  • Basic understanding of C# and RESTful API concepts
  • Visual Studio 2022 or later (for using Endpoints Explorer)

Project Setup

  1. Create a new Web API project:

    dotnet new webapi -o MinimalTodoApi
    cd MinimalTodoApi
    
  2. Install Entity Framework Core packages:

    We'll use EF Core for data persistence. Install the necessary packages:

    dotnet add package Microsoft.EntityFrameworkCore.SqlServer  # Or your preferred database provider
    dotnet add package Microsoft.EntityFrameworkCore.Design
    dotnet add package Microsoft.EntityFrameworkCore.Tools
    

Defining the Todo Model

Create a Models directory and add a Todo.cs file:

namespace MinimalTodoApi.Models;

public class Todo
{
    // Unique identifier for the Todo item
    public Guid Id { get; set; }

    // Name or description of the Todo item
    public string? Name { get; set; }

    // Indicates whether the Todo item is complete
    public bool IsComplete { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

This simple model defines the structure of our Todo items.

Setting up the Database Context

Create a Data directory and add TodoDb.cs:

using Microsoft.EntityFrameworkCore;
using MinimalTodoApi.Models;

namespace MinimalTodoApi.Data;

// Represents the database context for the Todo application
public class TodoDb : DbContext
{
    // Constructor that accepts DbContextOptions
    public TodoDb(DbContextOptions<TodoDb> options) : base(options) { }

    // Represents the collection of Todo items in the database
    public DbSet<Todo> Todos { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

This class sets up our database context using Entity Framework Core.

Configuring the Minimal API Endpoints (Program.cs)

Now, let's define our API endpoints within Program.cs:

using Microsoft.EntityFrameworkCore;
using MinimalTodoApi.Data;
using MinimalTodoApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add the database context to the services container.  This allows the database to be injected into the API endpoints.
builder.Services.AddDbContext<TodoDb>(options
    => options.UseSqlServer(builder.Configuration.GetConnectionString("MinimalTodo"))
    );

var app = builder.Build();

// Configure the API endpoints

// Get all todo items
app.MapGet("/todos", async (TodoDb db) =>
    await db.Todos.ToListAsync());

// Get completed todo items
app.MapGet("/todos/complete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());

// Get a specific todo item by ID
app.MapGet("/todos/{id}", async (Guid id, TodoDb db) =>
    await db.Todos.FindAsync(id)
        is Todo todo
            ? Results.Ok(todo)
            : Results.NotFound());

// Create a new todo item
app.MapPost("/todos", async (Todo todo, TodoDb db) =>
{
    db.Todos.Add(todo);
    await db.SaveChangesAsync();

    return Results.Created($"/todos/{todo.Id}", todo);
});

// Update an existing todo item
app.MapPut("/todos/{id}", async (Guid id, Todo inputTodo, TodoDb db) =>
{
    var todo = await db.Todos.FindAsync(id);
    if (todo is null) return Results.NotFound();

    todo.Name = inputTodo.Name;
    todo.IsComplete = inputTodo.IsComplete;
    await db.SaveChangesAsync();
    return Results.NoContent();
});

// Delete a todo item
app.MapDelete("/todos/{id}", async (Guid id, TodoDb db) =>
{
    if (await db.Todos.FindAsync(id) is Todo todo)
    {
        db.Todos.Remove(todo);
        await db.SaveChangesAsync();
        return Results.NoContent();
    }
    return Results.NotFound();
});

app.Run();
Enter fullscreen mode Exit fullscreen mode

Key improvements and explanations:

  • Clear separation of concerns: Models in Models, database context in Data.
  • Concise endpoint definitions: Minimal APIs make routing and logic clear.
  • Dependency Injection: The TodoDb context is injected directly into the endpoint handlers.
  • Asynchronous operations: Using async and await for non-blocking database calls.

Database Configuration

  1. Update appsettings.json:

    Configure your database connection string. For example, using SQL Server:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "ConnectionStrings": {
        "MinimalTodo": "Server=(localdb)\\mssqllocaldb;Database=MinimalTodo;Trusted_Connection=True;MultipleActiveResultSets=true"
      },
      "AllowedHosts": "*"
    }
    
  2. Create and apply migrations:

    dotnet ef migrations add InitialCreate
    dotnet ef database update
    

Running the API

dotnet run
Enter fullscreen mode Exit fullscreen mode

Your Todo API is now running!

Testing the API with Endpoints Explorer (Visual Studio)

Visual Studio provides a built-in tool to explore and test your API endpoints:

  1. Open Endpoints Explorer: In Visual Studio, go to View > Other Windows > Endpoints Explorer.
  2. Locate your API endpoints: The Endpoints Explorer will display a list of all available API endpoints in your project. You should see the /todos endpoints listed.
  3. Test the endpoints: You can right-click on an endpoint and select "Generate Request" to create a sample HTTP request. Modify the request as needed (e.g., add a request body for POST/PUT requests) and then click "Send Request" to test the endpoint. The response will be displayed in a separate window.

Image description

Image description

Conclusion

.NET Core Minimal APIs provide a powerful and elegant way to build APIs with minimal code. This Todo list example demonstrates the core concepts and provides a foundation for building more complex applications. Embrace the simplicity and efficiency of Minimal APIs in your next .NET project!

πŸ”— Useful Links
πŸ“˜ Official Docs: Minimal APIs in ASP.NET Core
πŸ“¦ GitHub Sample: Todo API with Minimal APIs

Top comments (0)