Building a Web API
Bring everything together to build a complete, working REST API with ASP.NET Core and EF Core.
Putting It All Together
You now have every piece needed to build a real REST API: controllers, routing, model binding, EF Core, and dependency injection. This lesson combines them into one complete example.
DTOs (Data Transfer Objects)
A DTO is a class shaped specifically for what an API exposes — often different from your database entity, to avoid leaking internal fields or over-fetching data.
public class TaskDto{ [Required, StringLength(100)] public string Title { get; set; } = ""; public bool IsComplete { get; set; }}A Complete API Controller
[ApiController][Route("api/[controller]")]public class TasksController : ControllerBase{ private readonly AppDbContext context;
public TasksController(AppDbContext context) { this.context = context; }
[HttpGet] public async Task<IActionResult> GetAll() { var tasks = await context.Tasks.ToListAsync(); return Ok(tasks); }
[HttpGet("{id}")] public async Task<IActionResult> GetById(int id) { var task = await context.Tasks.FindAsync(id); if (task == null) return NotFound(); return Ok(task); }
[HttpPost] public async Task<IActionResult> Create(TaskDto dto) { var task = new TaskItem { Title = dto.Title, IsComplete = dto.IsComplete }; context.Tasks.Add(task); await context.SaveChangesAsync(); return CreatedAtAction(nameof(GetById), new { id = task.Id }, task); }
[HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { var task = await context.Tasks.FindAsync(id); if (task == null) return NotFound();
context.Tasks.Remove(task); await context.SaveChangesAsync(); return NoContent(); }}Testing with Swagger
ASP.NET Core Web API projects include Swagger (via Swashbuckle) by default in development — it generates an interactive documentation page where you can try every endpoint directly in the browser.
Run the app and navigate to /swagger — you'll see every endpoint in this controller listed, with a "Try it out" button for testing requests without needing a separate tool like Postman.
FAQs
For small apps and learning, yes. Larger production apps often add a "service layer" between controllers and DbContext to keep controllers thin — a natural next step once you're comfortable with the basics.
Summary
- A complete API combines controllers, DTOs, EF Core, and DI.
- DTOs decouple your API's public shape from your database entities.
- Swagger provides interactive, auto-generated API documentation for testing.