design

Building a Simple REST API with .NET Core: Step-by-Step Guide

April 6, 2025

Ready to create your first .NET Core Web API? Follow this hands-on tutorial to build a fully functional REST API in minutes!


🚀 What We'll Build

✅ CRUD API for a Todo application

✅ Swagger/OpenAPI documentation

✅ Entity Framework Core database integration

✅ Proper REST conventions (status codes, HTTP methods)


🛠 Step 1: Create the Project

Run in your terminal:

dotnet new webapi -n TodoApi
cd TodoApi

Key files created:

  • Controllers/ (Where our API endpoints live)
  • Program.cs (Replaces Startup.cs in .NET 6+)

🏗 Step 2: Add Model & DbContext


1. Create Models/Todo.cs

public class Todo
{
    public int Id { get; set; }
    public string? Title { get; set; }
    public bool IsComplete { get; set; }
}


2. Add Entity Framework Core

dotnet add package Microsoft.EntityFrameworkCore.InMemory


3. Create Data/TodoContext.cs

public class TodoContext : DbContext
{
    public TodoContext(DbContextOptions<TodoContext> options)
        : base(options) { }

    public DbSet<Todo> Todos => Set<Todo>();
}


4. Register DbContext (In Program.cs)

builder.Services.AddDbContext<TodoContext>(opt => 
    opt.UseInMemoryDatabase("TodoList"));


🎯 Step 3: Build the Controller

Create Controllers/TodosController.cs

[ApiController]
[Route("[controller]")]
public class TodosController : ControllerBase
{
    private readonly TodoContext _context;

    public TodosController(TodoContext context)
    {
        _context = context;
    }

    // GET: /todos
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Todo>>> GetTodos()
    {
        return await _context.Todos.ToListAsync();
    }

    // GET: /todos/5
    [HttpGet("{id}")]
    public async Task<ActionResult<Todo>> GetTodo(int id)
    {
        var todo = await _context.Todos.FindAsync(id);
        return todo == null ? NotFound() : todo;
    }

    // POST: /todos
    [HttpPost]
    public async Task<ActionResult<Todo>> PostTodo(Todo todo)
    {
        _context.Todos.Add(todo);
        await _context.SaveChangesAsync();
        return CreatedAtAction(nameof(GetTodo), new { id = todo.Id }, todo);
    }
}


🔥 Step 4: Test Your API

  1. Run the app:
dotnet run


  1. Visit Swagger UI at https://localhost:5001/swagger
  2. Try these endpoints:
  • GET /todos - Get all todos
  • POST /todos - Add new todo
  • GET /todos/{id} - Get specific todo


💡 Best Practices Implemented

✔ Proper HTTP status codes (201 Created, 404 Not Found)

✔ Async/Await for scalability

✔ Clean separation of concerns

✔ Dependency Injection for DbContext

🚀 Next Steps

  • Add authentication with JWT
  • Connect to a real database (SQL Server, PostgreSQL)
  • Implement DTOs for better request/response handling

Full source code available on GitHub!

#DotNetCore #WebAPI #REST #CSharp #EntityFramework #BackendDevelopment

3 + 4 =