REST APIs with Web API
Advanced
25 min read
Lesson 5 of 6
While this whole site is built with Razor Pages (server-rendered HTML), ASP.NET Core also lets you build pure JSON APIs — useful for mobile apps (like the .NET MAUI module), JavaScript front-ends, or other services.
Creating a minimal API controller
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class StudentsController : ControllerBase
{
private readonly SchoolDbContext _context;
public StudentsController(SchoolDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<List<Student>>> GetAll()
{
return await _context.Students.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Student>> GetById(int id)
{
var student = await _context.Students.FindAsync(id);
if (student == null) return NotFound();
return student;
}
[HttpPost]
public async Task<ActionResult<Student>> Create(Student student)
{
_context.Students.Add(student);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetById), new { id = student.StudentId }, student);
}
[HttpPut("{id}")]
public async Task<IActionResult> Update(int id, Student student)
{
if (id != student.StudentId) return BadRequest();
_context.Entry(student).State = EntityState.Modified;
await _context.SaveChangesAsync();
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var student = await _context.Students.FindAsync(id);
if (student == null) return NotFound();
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return NoContent();
}
}
Registering controllers in Program.cs
builder.Services.AddControllers();
// ...
app.MapControllers();
REST verbs at a glance
| Verb | Meaning |
|---|---|
| GET | Read data |
| POST | Create new data |
| PUT | Replace/update existing data |
| DELETE | Remove data |
Testing the API
Use the Swagger UI (enabled by default in new API projects at
/swagger), or a tool like Postman, to call these endpoints
without writing a client first.
Key Takeaway
REST APIs allow your application to serve data to mobile apps, frontends, and other services.