Skip to content
Tutorials Center
My learning

Topics

Lesson 172 of 182 ยท Projects

Project: Inventory REST API

Build an inventory REST API with ASP.NET Core minimal APIs in four stages: endpoints, dependency injection with validation, filters and problem details, then an automated HttpClient test suite.

Almost every web developer builds an API like this one at some point: a list of things, with endpoints to create, read, change and delete them, plus a few rules. An inventory API is a good version of the exercise because it has real rules. A SKU (stock-keeping unit) must be unique. A price must be positive. Stock must never go below zero, even when many requests change it at once.

You build it in four stages, and every stage is a complete program that starts a real Kestrel web server on the loopback address and talks to it with HttpClient in the same process. In stage 1 you map the first endpoints over an in-memory list and see exactly what is wrong with that. In stage 2 you move the data behind an interface, let dependency injection supply it, and add validation with proper status codes. In stage 3 you add route groups, endpoint filters, an API key read through the options pattern, a stock-adjustment endpoint, and a global error handler that speaks ProblemDetails. In stage 4 you restructure the app so that a test can start a fresh copy of it, then write an automated test suite that uses nothing but HttpClient.

This project builds on Minimal APIs, Dependency Injection and Validation and Problem Details. Read those first if the vocabulary is new.

Web examples in this track use explicit using lines. The editor's implicit usings cover the base class library only, not ASP.NET Core, so each program starts with using Microsoft.AspNetCore.Builder; and friends. In a real web project (Microsoft.NET.Sdk.Web) those namespaces are imported for you. Every program also calls builder.Logging.ClearProviders() to keep request logs out of the output, and ends by stopping the server.

The API we are building

TEXT
GET    /api/products?category=&maxQuantity=   list, optionally filtered
GET    /api/products/{id}                     one product, or 404
POST   /api/products                          create: 201 + Location, 400 if invalid, 409 if the SKU exists
PUT    /api/products/{id}                     replace
DELETE /api/products/{id}                     204, or 404
POST   /api/products/{id}/stock               add or remove stock: {"delta": -3, "reason": "sold"}

Reading is open to everyone. Writing needs an X-Api-Key header. Errors are reported as application/problem+json documents, the standard JSON shape for HTTP errors (RFC 9457), so clients see the same structure for every failure.

Stage 1: the first endpoints, and what is wrong with them

The shortest possible version keeps the data in a List<Product> local variable and maps handlers straight to it. This is fine for a sketch, and the program is useful for a different reason: it shows the problems that the next stages solve.

C# Stage 1: endpoints over a plain list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The happy path works: GET returns the list, an unknown id gives 404 Not Found, and POST returns 201 Created with a Location header pointing at the new resource. Everything else is a list of defects:

  1. No validation. The "nonsense" product (empty name, price -5, quantity -1) was accepted and stored. A second product with an existing SKU was accepted too, so the SKU is not unique. Rules must live somewhere the handler cannot forget.
  2. The data is not thread safe. Kestrel runs requests on many threads at once, and List<T> is not safe for concurrent writes. Two simultaneous POSTs can compute the same id with Max() + 1 or corrupt the list.
  3. Logic lives in the lambdas. Rules for finding, adding and replacing are mixed into HTTP code. You cannot reuse them elsewhere or test them without a web server.
  4. Errors are plain 404 with no body. Clients cannot tell what went wrong.
  5. Ids come from Max() + 1. After a delete of the last item, an id would be reused.

The next stage answers 1, 2, 3 and 5. Stage 3 answers 4.

Stage 2: a repository, dependency injection and validation

The fix for the "logic in lambdas" problem is the pattern you already used in the other projects: put the data behind an interface. Handlers ask for IProductRepository as a parameter, and ASP.NET Core's dependency injection container creates it and passes it in. The handler no longer knows or cares whether the data is in memory, in SQL or in a test fake (dependency injection).

A few design points before the code:

  • The repository is registered as a singleton, because our "database" is the in-memory object and every request must see the same one. A repository for a real database would normally be scoped (one per request) because it uses a per-request DbContext. The lifetime follows the thing you hold, not a rule of thumb.
  • All access is behind one Lock, and ids come from a counter that only moves forward, so ids are never reused.
  • Operations return a result (StoreResult) instead of throwing for expected situations like "duplicate SKU". Bad data is a normal outcome of a public API, so it should be an ordinary return value, and the endpoint can turn it into the right status code (exceptions).
  • Validation is a service too. IValidator<T> returns a dictionary of field -> messages, which is exactly the shape TypedResults.ValidationProblem wants. In this stage the handler calls it by hand; stage 3 pulls that out into a reusable filter.
  • Typed results. Instead of the untyped IResult, each handler declares what it can return: Results<Created<Product>, ValidationProblem, ProblemHttpResult>. The compiler then checks the handler, and OpenAPI tools can describe every status code from the signature alone (minimal APIs).
C# Stage 2: repository, DI, validation and status codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Take the output apart, because every status code here is a decision:

  • 200 OK for a successful read. 404 Not Found when the id is valid but absent.
  • GET /products/abc is a 404, not a 500 or 400. The route {id:int} has an int constraint, so abc simply does not match the route at all. Constraints are cheap, but they produce 404; if you want a friendly 400 for a malformed id, take a string and parse it yourself.
  • 201 Created plus Location on a successful POST, so a client can follow the link without guessing.
  • 400 Bad Request with errors for invalid input. The body is an HttpValidationProblemDetails document: a title, a status, and an errors object mapping each field to its messages. The client can show each message beside the right input.
  • 409 Conflict for the duplicate SKU. The data was well formed, but it conflicts with the current state of the server. Many APIs wrongly return 400 here. The difference matters: a 400 means "fix your request", a 409 means "the request was fine, but the world disagrees".
  • 204 No Content for a delete, with no body; deleting the same product again gives 404.
  • The regex is a static readonly field, built once and reused by every request. Constructing a Regex per call would re-parse the pattern each time. In a normal project you would write [GeneratedRegex(...)] on a partial method instead, which compiles the pattern at build time; the lesson editor has no source generators, so the plain field is used here (regular expressions).
  • Model binding. ProductInput input is a complex type, so it is read from the JSON body. string? category and int? maxQuantity are simple types, so they come from the query string, and being nullable makes them optional (routing and binding).

Never trust the shape of a request body just because your own C# type says string Sku is non-nullable. Nullable annotations are compile-time hints only. JSON that omits sku produces a record whose Sku is null at runtime, which is why the validator tests input.Sku is null first. Validate every field of every public input.

Stage 3: groups, filters, options, stock and problem details

Stage 2 works, but it has a few smells that will worsen as the API grows: the /products prefix is repeated on every route, validation code sits in the handler, and there is no protection for the write endpoints. Stage 3 fixes these with the tools minimal APIs give you:

  1. A route group (app.MapGroup("/api/products")) shares the prefix, and also shares filters, tags and metadata.
  2. An endpoint filter wraps a handler. It runs before the handler, can inspect the arguments, and can short-circuit by returning a result without calling next. We write two: ValidationFilter<T>, which finds the argument of type T and validates it, and ApiKeyFilter. Two small extension methods, .WithValidation<T>() and .RequireApiKey(), make endpoint declarations read like a specification.
  3. The options pattern supplies the API key. The key sits in configuration under Inventory:ApiKey; an InventoryOptions class is bound to that section; filters ask for IOptions<InventoryOptions>. Here the configuration is in memory; in production it would come from environment variables or a secrets store, never from source code (configuration and options).
  4. A stock endpoint, POST /{id}/stock, with a signed Delta. Selling three items is -3; a delivery is +50. The repository applies the change under the lock and refuses to go below zero, which makes the check-and-update atomic: two clients selling the last item cannot both succeed.
  5. Global error handling. AddProblemDetails() plus UseExceptionHandler() turns any unhandled exception into a 500 with a problem+json body, without leaking the exception message or stack trace to the client.

The API key comparison deserves a note. string == stops at the first difference, so response timing can reveal how many leading characters were right. CryptographicOperations.FixedTimeEquals compares all bytes in constant time. It is a small habit with no downside.

The demo script exercises every endpoint, including the failure cases.

C# Stage 3: route group, filters, API key, stock and error handling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

There is a lot to study in this output:

  • Filter order is declaration order. .RequireApiKey().WithValidation<ProductInput>() means the key is checked first. An anonymous caller therefore learns nothing about validation rules. Try swapping them and call POST without a key and with an invalid body.
  • 401 versus 403. A missing or wrong key is 401 Unauthorized ("I don't know who you are"). 403 Forbidden means "I know who you are, and you may not do this". The names are confusingly historic; the meanings are not.
  • The 500 response is deliberately boring. The exception message was secret internal detail; the client sees only a generic problem title and status. Details belong in your logs, not in responses. (The real body also contains a traceId that changes on every request, so the demo prints only the stable parts.)
  • WouldGoNegative is a business conflict (409), not a validation error. The request was well formed, but it conflicts with the current stock.
  • The stock check is atomic. AdjustStock reads, checks and writes inside one lock. If the check were done in the endpoint (Get, compare, then Replace), two requests could both pass the check and both write, a race condition called check-then-act. Stage 4 proves the fix with 200 simultaneous requests.
  • product with { Quantity = ... } creates a new record instead of editing the stored one. Another thread that is still reading the old Product never sees a half-updated object.
  • Local functions in top-level code. Duplicate is declared in the statements and used by several endpoints. Because it is a local function it can be called before its declaration line.
  • Replace keeps the id and rebuilds the other fields, which is what PUT means: the whole resource is replaced. A partial update would use PATCH.
  • Why a filter and not middleware? Middleware sees every request. Filters are attached to specific endpoints and receive the already-bound arguments, so ValidationFilter<T> can see the deserialized ProductInput. Use middleware for things that apply to everything (logging, CORS), filters for endpoint-specific rules (middleware).

Deciding which status code to return gets easier with three questions. Was the request understood and well formed? If not, 400. Is the caller identified and allowed? If not, 401 or 403. Does the request clash with the state of the resource? Then 409. Only when none of these applies is it a success (200, 201 or 204) or a 404 for a missing resource.

Stage 4: a testable app and an HttpClient test suite

The program so far starts exactly one server on a fixed port. For automated tests you want the opposite: many fresh, isolated copies of the app, each on its own free port, each with the data you choose. That calls for a small restructure: move the setup into a method InventoryApp.Create(url, configureServices) that returns a configured WebApplication. Program.cs becomes three lines (create, seed, run), and a test calls Create with the URL http://127.0.0.1:0, which tells Kestrel "pick any free port". After StartAsync, app.Urls contains the real address.

The configureServices callback is the testing seam. A test can replace any service. Registering a service type a second time makes the last registration win, so a test can substitute a repository that throws and prove the error handler works without writing a special failing endpoint.

In a real project you would use xUnit and WebApplicationFactory<Program>, which does the same thing in-process without even opening a socket (xUnit and NUnit). Those packages are not available here, so this suite is plain HttpClient against real Kestrel instances. It is the same technique, with a few more lines of setup, and it tests the full pipeline: routing, binding, filters, serialization.

A test helper TestServer starts an app and gives a client with the API key. It implements IAsyncDisposable so that await using var server = ... stops the app at the end of each test (disposal). The suite checks the status codes, the headers, the error shapes and, in the last test, a real concurrency property: with 100 units in stock, 200 parallel requests each removing one unit must produce exactly 100 successes and 100 conflicts, and a final quantity of zero. That outcome is independent of how the threads interleave, which makes it a reliable test.

C# Stage 4: the testable app and its test suite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Study how the pieces cooperate:

  • Port 0 and app.Urls. Binding to http://127.0.0.1:0 asks the operating system for any free port, so tests never collide with each other or with something else on the machine. After StartAsync, app.Urls holds the real address.
  • One app per test. Each test gets its own server and its own empty repository. No test can leave data behind for the next one, which is what makes test order irrelevant. Starting a Kestrel instance takes a few tens of milliseconds, which is fine for a suite of this size; a very large suite shares a server and resets the data between tests.
  • The seam, configureServices. The ExplodingRepository replaces the real one for one test. The test asserts two things about the 500: the media type is application/problem+json, and the secret in the exception message is not in the response body. A security property, tested.
  • Why the last test is trustworthy. If AdjustStock did its check outside the lock, some runs would produce 101 successes or a negative quantity, and the test would fail intermittently. Because the check and the write are one atomic step, the result is always exactly 100 and 100. You can verify the claim by temporarily moving the quantity check out of the lock and running the suite several times.
  • await using var server guarantees the server is stopped even if an assertion throws halfway through a test.
  • Test names read as a specification. A teammate who knows nothing about the code can read the list of passing tests and learn the API's rules.

Keep two kinds of tests in a real project. Unit tests call the repository and validators directly: they are fast and pinpoint a bug. API tests, like the ones above, prove that routing, binding, filters and serialization are wired correctly. A bug such as "the key filter was never added to DELETE" can only be found by the second kind.

Ideas for extending the API

  1. Paging and sorting. Add page, pageSize and sort query parameters, return a Link/X-Total-Count header, and cap pageSize so one client cannot ask for a million rows.
  2. Optimistic concurrency. Add a Version to Product, return it as an ETag, and require If-Match on PUT. A stale update gets 412 Precondition Failed.
  3. A real database. Write a second IProductRepository over ADO.NET or Entity Framework Core and run the same API tests against both. If the tests are good, nothing in the endpoints changes.
  4. Real authentication. Replace the API key with JWT bearer tokens and roles (authentication and authorization), so readers, clerks and admins have different permissions.
  5. OpenAPI. Because every handler declares typed results, generating an OpenAPI document needs one line and gives you a client in any language.
  6. Caching. GET /api/products/{id} with an ETag and Cache-Control lets clients and proxies avoid repeat downloads (caching and HttpClientFactory).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client sends a well-formed POST whose SKU already exists. Which status code fits best?

    The request itself is valid, but it conflicts with the current state of the server. 400 means the request must be fixed, 404 means the resource is missing, and 500 would wrongly blame the server.
  2. 2. Why does AdjustStock check the quantity and update it inside one lock instead of the endpoint calling Get, comparing, then Replace?

    With separate steps, two threads can both see enough stock and both subtract, overselling. Doing the check and the write in one critical section makes the pair atomic.
  3. 3. What does an endpoint filter that returns a result without calling next do?

    Filters wrap the handler. Returning a value instead of awaiting next(context) ends processing at that point, which is how the key and validation filters reject requests.
  4. 4. In the test suite, why does each test call TestServer.StartAsync with the URL http://127.0.0.1:0?

    Binding to port 0 lets the OS assign any free port. app.Urls then reports the real address, so tests can run without fighting over a fixed port.
  5. 5. Why does the validator test input.Sku is null even though ProductInput declares Sku as a non-nullable string?

    Non-nullable reference types are compile-time hints. The JSON deserializer can still leave a property null when the field is missing, so public input must be validated defensively.

Summary

  • Start with the simplest endpoints to see the gaps, then close them one at a time: validation, thread safety, structure, error handling.
  • Put data access behind an interface and let dependency injection supply it; choose the lifetime (singleton, scoped, transient) from what the service holds.
  • Return typed results and the right status code: 201 + Location for creation, 400 for malformed input, 401/403 for access, 404 for missing, 409 for conflicts with current state, 204 for empty success.
  • Use route groups for shared prefixes, endpoint filters for per-endpoint rules such as validation and API keys, and AddProblemDetails() with UseExceptionHandler() so every error has the same shape and no internals leak.
  • Make check-then-update operations atomic (one lock, or a database transaction), and read secrets through the options pattern.
  • Build the app in a factory method with a service-override hook, start it on port 0, and test the whole pipeline with HttpClient. Assert invariants for concurrent behaviour.

Next: Project: Text Adventure Engine