Lab 1: The Public Menu
45 minutes · Ends at checkpoint-1
In this lab you build the read side of Roastery: a product catalog served from an in-memory list. Persistence comes in Module 2; the HTTP contract you define here will not change when it does.
Starting point
You build every lab in src/Roastery.Api. (src/00-start was only the pre-workshop environment check.) From the repo root:
git switch -c my-roastery start
cd src/Roastery.Api
dotnet run --launch-profile https
The https profile listens on https://localhost:7181, which every .http file uses. Plain dotnet run picks the first profile, which is HTTP-only on :5181.
Every command and file path below is relative to src/Roastery.Api. The starter holds a Program.cs with one /health endpoint and seed data in Data/Seed.cs.
Open http/module-1.http (at the repo root) in your editor. Every request in this lab is already written there.
Step 1: The domain and a catalog service
Create Models/Product.cs:
namespace Roastery.Api.Models;
public enum Roast { Light, Medium, Dark }
public class Product
{
public int Id { get; set; }
public required string Name { get; set; }
public Roast Roast { get; set; }
public decimal Price { get; set; }
public int StockQuantity { get; set; }
}
Create Contracts/ProductContracts.cs with the DTO, the create request, and a query record:
namespace Roastery.Api.Contracts;
public record ProductDto(int Id, string Name, string Roast, decimal Price, bool InStock);
public record CreateProductRequest(string Name, string Roast, decimal Price, int StockQuantity);
/// <summary>Query-string filters for the product list, bound with [AsParameters].</summary>
public record ProductQuery(string? Roast, bool? InStock);
Create Contracts/Mapping.cs with the ToDto() extension:
using Roastery.Api.Models;
namespace Roastery.Api.Contracts;
public static class Mapping
{
public static ProductDto ToDto(this Product p) =>
new(p.Id, p.Name, p.Roast.ToString(), p.Price, p.StockQuantity > 0);
}
Create Services/IProductCatalog.cs:
using Roastery.Api.Contracts;
using Roastery.Api.Models;
namespace Roastery.Api.Services;
public interface IProductCatalog
{
Task<IReadOnlyList<Product>> ListAsync(string? roast, bool? inStock, CancellationToken ct);
Task<Product?> FindAsync(int id, CancellationToken ct);
Task<Product> AddAsync(CreateProductRequest request, CancellationToken ct);
}
Then create Services/InMemoryProductCatalog.cs, which loads the five products from Data/Seed.cs and assigns ids 1 to 5. Write it yourself or paste it from the panel.
using Roastery.Api.Contracts;
using Roastery.Api.Data;
using Roastery.Api.Models;
namespace Roastery.Api.Services;
/// <summary>Lab 1 catalog. Replaced by EfProductCatalog in Lab 2.</summary>
public class InMemoryProductCatalog : IProductCatalog
{
private readonly List<Product> _products;
private readonly Lock _lock = new();
public InMemoryProductCatalog()
{
_products = Seed.Products
.Select((p, i) => new Product
{
Id = i + 1,
Name = p.Name,
Roast = Enum.Parse<Roast>(p.Roast),
Price = p.Price,
StockQuantity = p.Stock
})
.ToList();
}
public Task<IReadOnlyList<Product>> ListAsync(string? roast, bool? inStock, CancellationToken ct)
{
lock (_lock)
{
IEnumerable<Product> query = _products;
if (roast is not null && Enum.TryParse<Roast>(roast, true, out var r))
query = query.Where(p => p.Roast == r);
if (inStock is true)
query = query.Where(p => p.StockQuantity > 0);
return Task.FromResult<IReadOnlyList<Product>>(query.ToList());
}
}
public Task<Product?> FindAsync(int id, CancellationToken ct)
{
lock (_lock) return Task.FromResult(_products.FirstOrDefault(p => p.Id == id));
}
public Task<Product> AddAsync(CreateProductRequest request, CancellationToken ct)
{
lock (_lock)
{
var product = new Product
{
Id = _products.Count == 0 ? 1 : _products.Max(p => p.Id) + 1,
Name = request.Name,
Roast = Enum.Parse<Roast>(request.Roast, true),
Price = request.Price,
StockQuantity = request.StockQuantity
};
_products.Add(product);
return Task.FromResult(product);
}
}
}
Register it in Program.cs. Service registrations go after CreateBuilder and before builder.Build():
using Roastery.Api.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IProductCatalog, InMemoryProductCatalog>();
var app = builder.Build();
// …
It is a singleton because the list is the database: a scoped or transient catalog would reseed on every request and lose your POST. One instance shared by concurrent requests is also why the class takes a lock.
Step 2: The products group
Create Endpoints/ProductEndpoints.cs:
using System.Diagnostics;
using Microsoft.AspNetCore.Http.HttpResults;
using Roastery.Api.Contracts;
using Roastery.Api.Services;
namespace Roastery.Api.Endpoints;
public static class ProductEndpoints
{
public static RouteGroupBuilder MapProductEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/api/products").WithTags("Products");
group.MapGet("/", GetProducts)
.WithName("GetProducts")
.WithSummary("List products, optionally filtered by roast and stock.");
group.MapGet("/{id:int}", GetProduct)
.WithName("GetProduct")
.WithSummary("Get a single product.");
group.MapPost("/", CreateProduct)
.WithName("CreateProduct")
.WithSummary("Add a product to the menu.");
return group;
}
static async Task<Ok<List<ProductDto>>> GetProducts(
[AsParameters] ProductQuery query, IProductCatalog catalog, CancellationToken ct)
{
var products = await catalog.ListAsync(query.Roast, query.InStock, ct);
return TypedResults.Ok(products.Select(p => p.ToDto()).ToList());
}
static async Task<Results<Ok<ProductDto>, NotFound>> GetProduct(
int id, IProductCatalog catalog, CancellationToken ct)
{
var product = await catalog.FindAsync(id, ct);
return product is null ? TypedResults.NotFound() : TypedResults.Ok(product.ToDto());
}
static async Task<CreatedAtRoute<ProductDto>> CreateProduct(
CreateProductRequest request, IProductCatalog catalog, CancellationToken ct)
{
var product = await catalog.AddAsync(request, ct);
return TypedResults.CreatedAtRoute(product.ToDto(), "GetProduct", new { id = product.Id });
}
}
System.Diagnostics is for the Stopwatch you add in Step 4.
In Program.cs, add using Roastery.Api.Endpoints; at the top and call app.MapProductEndpoints(); after builder.Build(), next to the /health mapping.
Restart the app (Ctrl+C, then dotnet run --launch-profile https again) and send these requests from module-1.http:
Step 3: Create and link
Send Create a product. You should get 201 Created with:
Location: https://localhost:7181/api/products/6
{"id":6,"name":"Kenya AA","roast":"Light","price":19.50,"inStock":true}
GET that location and you get the same product back. The id is 6 because the seed holds five; it resets every time you restart the app.
warning
If you get an exception mentioning a route named GetProduct, the .WithName("GetProduct") call is missing or misspelled. CreatedAtRoute resolves the name at runtime.
Now change "roast" in the request body to "Espresso" and send it again. You get a 500: Enum.Parse in AddAsync throws on a roast that does not exist. Nothing validates the request yet. That is the first job of Module 2.
Step 4: A timing filter on the group
Add this to MapProductEndpoints before return group;:
group.AddEndpointFilter(async (context, next) =>
{
var sw = Stopwatch.StartNew();
var result = await next(context);
context.HttpContext.Response.Headers["X-Elapsed-Ms"] = sw.ElapsedMilliseconds.ToString();
return result;
});
Send any products request and look for X-Elapsed-Ms in the response headers. Expect 0 or 1; an in-memory list is fast.
Now watch the order things run in. Add Console.WriteLine("filter"); at the top of the filter and Console.WriteLine("handler"); at the top of GetProducts. In Program.cs, after builder.Build(), add a small inline middleware:
app.Use(async (ctx, next) =>
{
Console.WriteLine("middleware");
await next();
});
Send List all products. The console prints middleware, then filter, then handler. Middleware wraps everything; the filter wraps only the handler. Remove the three logging lines and the middleware when you are done; checkpoint-1 does not have them.
Step 5: Read the OpenAPI document
Add the packages, pinned to the versions the checkpoint uses:
dotnet add package Microsoft.AspNetCore.OpenApi --version 10.0.11
dotnet add package Scalar.AspNetCore --version 2.17.1
Register OpenAPI before builder.Build(), and map the document and UI after it:
using Scalar.AspNetCore;
builder.Services.AddOpenApi(); // before builder.Build()
// …
app.MapOpenApi(); // after builder.Build()
app.MapScalarApiReference();
Restart and browse to https://localhost:7181/scalar/v1. Find GetProduct and confirm it shows both 200 (with the ProductDto schema) and 404.
Now find the line in Program.cs marked // BUG: wrong Produces. The starter's /health endpoint declares .Produces<int>(200) even though it returns a string, and the OpenAPI document dutifully reports an integer. Replace the Produces call with .ExcludeFromDescription() (a health probe does not belong in the public API document) and restart. Health check still returns 200 Healthy; the endpoint just no longer appears in Scalar or /openapi/v1.json. The lesson: metadata you write by hand can lie; metadata inferred from TypedResults cannot.
Your Program.cs should now match this:
using Roastery.Api.Endpoints;
using Roastery.Api.Services;
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
builder.Services.AddSingleton<IProductCatalog, InMemoryProductCatalog>();
var app = builder.Build();
app.UseHttpsRedirection();
app.MapGet("/health", () => "Healthy").ExcludeFromDescription();
app.MapProductEndpoints();
app.MapOpenApi();
app.MapScalarApiReference();
app.Run();
Step 6: Exercise everything
Restart the app so the catalog is back to its seed, then run through every request in module-1.http one more time. The expected status for each is written in the comment above the request.
Stretch goals
- Add
GET /api/products/{id}/imagethat returnsTypedResults.PhysicalFile(...)for an image inwwwroot/images, with404if the file is missing. - Add
app.MapFallback(...)that returns aProblemDetailswith status404and a friendly message for any unmatched route. - Add a route constraint so
/{id:int:min(1)}rejects zero and negative ids, and see what the client receives.
Common pitfalls
- Unconstrained route parameters. With
/{id}and anint idparameter,/api/products/abcmatches the route, fails to bind, and returns400. With/{id:int}the route does not match at all and the client gets404. (A literal segment like/featuredalways beats a parameter, constraint or not, so the constraint is about bad input, not about keeping routes apart.) ResultsversusTypedResults. Both compile; only the typed version populates OpenAPI and gives you a compile-time contract.- Filters versus middleware. Filters run after binding and can see the handler's arguments; middleware runs before binding and cannot. Choose based on what you need to see.
- Forgetting to restart.
dotnet rundoes not pick up code changes. Restart after each edit, or usedotnet watch run --launch-profile https.
Checkpoint
Commit your work on your my-roastery branch:
git add -A && git commit -m "Lab 1 complete"
If you fell behind, commit what you have, then start Lab 2 from the checkpoint on a fresh branch:
git switch -c my-roastery-2 checkpoint-1
Next: Module 2: Data, Validation, and the Shape of a Good API