ASP.NET Core Project: Build a Notes Web API
On this page
Learning Objective
Assemble the phase into a working, tested REST API with grouped endpoints, validated request types, standard error responses, and integration tests using WebApplicationFactory, while leaving a clean seam for the database work in Phase 4 and the authentication work in Phase 5.
Concept Explanation
This project brings together the last ten days. You will build a Notes API with five operations: list notes, get one note, create, update, and delete. It stores data in memory behind an interface, so the next phase can swap in SQL Server by changing a registration. It uses grouped minimal API endpoints, DTOs rather than entities, DataAnnotations validation, the global exception handler, and the hardening middleware from Day 19. Most importantly, it has tests that call the real HTTP pipeline, which is the fastest way to prove the whole stack fits together.
Begin with the design decisions that hold up later. The NoteEntity is internal to the server and includes an OwnerId, unused for now but already present, so that adding per-user access control in Phase 5 changes behavior rather than data shape. The request types, CreateNoteRequest and UpdateNoteRequest, expose only writable fields. The response type, NoteDto, excludes the OwnerId. The store is an INoteStore whose in-memory implementation uses a concurrent dictionary and an atomic counter, because the API handles simultaneous requests and a plain dictionary would corrupt under load. Registering it as a singleton is correct here precisely because it is thread-safe and the data is meant to be global.
Testing through the pipeline uses WebApplicationFactory of Program from the Microsoft.AspNetCore.Mvc.Testing package. It boots your application in memory, gives you an HttpClient wired to it, and lets you replace services for the test. Each test then sends a real request and asserts on the status code, headers, and body. Compared with unit tests that call handler methods directly, these tests also cover routing, binding, validation, serialization, and middleware, which is where many integration bugs live. For this to work, Program.cs ends with a public partial class Program declaration so the test project can reference the entry point.
Write the tests for the failure modes as deliberately as the happy path: invalid input returns 400 with an errors dictionary, an unknown id returns 404 with a problem body, an oversized body is refused, and no response reveals a stack trace. Failure-path tests are how you turn the security and robustness ideas from this phase into guarantees that survive refactoring. When Phase 5 adds authentication, these same tests will gain a helper that supplies a signed-in test user, and new tests will prove that anonymous and cross-user requests are rejected.
| Operation | Method and route | Success | Failure cases |
|---|---|---|---|
| List notes | GET /api/notes | 200 with array | None expected |
| Get a note | GET /api/notes/{id} | 200 with NoteDto | 404 when missing |
| Create a note | POST /api/notes | 201 with Location header | 400 invalid body |
| Update a note | PUT /api/notes/{id} | 200 with NoteDto | 400 invalid, 404 missing |
| Delete a note | DELETE /api/notes/{id} | 204 no content | 404 missing |
| Any failure | Any | Problem details JSON | Never a stack trace |
Worked Example: The Endpoints, the Store and the Integration Tests
The listing shows the request types, the store, the endpoint group, and three integration tests.
public sealed class NoteEntity
{
public int Id { get; init; }
public string OwnerId { get; init; } = "anonymous"; // wired up in Phase 5
public string Title { get; set; } = "";
public string? Body { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
}
public record CreateNoteRequest([property: Required, StringLength(200, MinimumLength = 1)] string Title,
[property: StringLength(10_000)] string? Body);
public record UpdateNoteRequest([property: Required, StringLength(200, MinimumLength = 1)] string Title,
[property: StringLength(10_000)] string? Body);
public record NoteDto(int Id, string Title, string? Body, DateTimeOffset UpdatedAt)
{
public static NoteDto From(NoteEntity n) => new(n.Id, n.Title, n.Body, n.UpdatedAt);
}
public interface INoteStore
{
IReadOnlyList<NoteEntity> List();
NoteEntity? Find(int id);
NoteEntity Add(string title, string? body);
bool Remove(int id);
}
public sealed class InMemoryNoteStore(TimeProvider clock) : INoteStore
{
private readonly ConcurrentDictionary<int, NoteEntity> _notes = new();
private int _nextId;
public IReadOnlyList<NoteEntity> List() => _notes.Values.OrderBy(n => n.Id).ToList();
public NoteEntity? Find(int id) => _notes.GetValueOrDefault(id);
public bool Remove(int id) => _notes.TryRemove(id, out _);
public NoteEntity Add(string title, string? body)
{
var id = Interlocked.Increment(ref _nextId); // atomic, safe under concurrency
var note = new NoteEntity { Id = id, Title = title, Body = body, UpdatedAt = clock.GetUtcNow() };
_notes[id] = note;
return note;
}
}
public static class NoteEndpoints
{
public static void MapNoteEndpoints(this IEndpointRouteBuilder app)
{
var g = app.MapGroup("/api/notes").WithTags("Notes");
g.MapGet("/", (INoteStore s) => TypedResults.Ok(s.List().Select(NoteDto.From)));
g.MapGet("/{id:int}", Results<Ok<NoteDto>, NotFound> (int id, INoteStore s) =>
s.Find(id) is { } n ? TypedResults.Ok(NoteDto.From(n)) : TypedResults.NotFound());
g.MapPost("/", (CreateNoteRequest r, INoteStore s) =>
{
var n = s.Add(r.Title.Trim(), r.Body);
return TypedResults.Created($"/api/notes/{n.Id}", NoteDto.From(n));
});
g.MapPut("/{id:int}", Results<Ok<NoteDto>, NotFound> (int id, UpdateNoteRequest r, INoteStore s, TimeProvider clock) =>
{
if (s.Find(id) is not { } n) return TypedResults.NotFound();
n.Title = r.Title.Trim(); n.Body = r.Body; n.UpdatedAt = clock.GetUtcNow();
return TypedResults.Ok(NoteDto.From(n));
});
g.MapDelete("/{id:int}", Results<NoContent, NotFound> (int id, INoteStore s) =>
s.Remove(id) ? TypedResults.NoContent() : TypedResults.NotFound());
}
}
// Program.cs registrations and the seam for tests
builder.Services.AddValidation();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<INoteStore, InMemoryNoteStore>();
// ... exception handler, hardening middleware, app.MapNoteEndpoints();
public partial class Program;public class NotesApiTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client = factory.CreateClient();
[Fact]
public async Task Create_returns_201_with_location()
{
var response = await _client.PostAsJsonAsync("/api/notes", new { title = "First", body = "Hello" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.NotNull(response.Headers.Location);
}
[Fact]
public async Task Blank_title_returns_400_problem_with_field_errors()
{
var response = await _client.PostAsJsonAsync("/api/notes", new { title = "", body = "x" });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var problem = await response.Content.ReadFromJsonAsync<ValidationProblemDetails>();
Assert.Contains("Title", problem!.Errors.Keys, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public async Task Unknown_id_returns_404_and_never_leaks_internals()
{
var response = await _client.GetAsync("/api/notes/99999");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("at Notes", body); // no stack trace fragments
}
}Run dotnet test, then extend the project with a maximum page size on the list endpoint and a test that proves an oversized body is rejected. Those two additions preview Days 24 and 28.
Real-World Examples
- Microsoft's documentation has recommended WebApplicationFactory-based integration tests since ASP.NET Core 2.1, and the ASP.NET Core team tests the framework itself this way. Booting the whole application in memory, with real routing, binding, and middleware, catches the class of bugs that isolated unit tests structurally cannot see.
- The RealWorld project publishes a shared specification for a Medium-style application, an API plus a frontend, and community implementations exist for dozens of backend and frontend frameworks, including ASP.NET Core and React. It is a good exercise after this course for measuring your skills against a standard specification.
Review Questions & Answers
The store is a singleton used by many concurrent requests, and a plain Dictionary is not thread-safe, so simultaneous writes can corrupt it or throw. An unsynchronized counter can hand the same id to two requests. The concurrent collection and the atomic increment make those operations safe without explicit locking.
It runs the actual pipeline, so it exercises routing, parameter binding, JSON serialization, validation, exception handling, and middleware such as security headers. Bugs often live at those seams, for example a route constraint that does not match or a validation rule that is never triggered. Unit tests still have value for pure logic, but they cannot prove the wiring.
It anticipates per-user data ownership, so that adding authorization in Phase 5 changes queries and checks rather than the shape of stored data. Designing the entity around who owns a record early avoids a disruptive migration later, and reminds you that every read and write of a note will eventually need an ownership check.
Failure behavior is where security and reliability rules live, and it is the behavior most likely to regress silently during refactoring. A test that asserts an invalid body returns a structured 400 and that a missing note returns a 404 without internals locks those guarantees in. Happy-path tests alone would pass even if validation and error handling were removed.