
Ready to create your first .NET Core Web API? Follow this hands-on tutorial to build a fully functional REST API in minutes!
✅ CRUD API for a Todo application
✅ Swagger/OpenAPI documentation
✅ Entity Framework Core database integration
✅ Proper REST conventions (status codes, HTTP methods)
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+)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"));
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);
}
}
dotnet run
https://localhost:5001/swaggerGET /todos - Get all todosPOST /todos - Add new todoGET /todos/{id} - Get specific todo✔ Proper HTTP status codes (201 Created, 404 Not Found)
✔ Async/Await for scalability
✔ Clean separation of concerns
✔ Dependency Injection for DbContext
Full source code available on GitHub!
#DotNetCore #WebAPI #REST #CSharp #EntityFramework #BackendDevelopment