Exercise 1: Minimal API Basics
Objective
Build a simple Minimal API for managing a product catalog.
Requirements
- Create a new ASP.NET Core Web API project
- Implement CRUD endpoints using Minimal APIs
- Use in-memory storage (List<Product>)
- Return appropriate HTTP status codes
Steps
1. Create Project
dotnet new web -n MinimalApiBasics
cd MinimalApiBasics
2. Create Product Model
public record Product(int Id, string Name, decimal Price);
3. Implement Endpoints
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// In-memory storage
var products = new List<Product>();
var nextId = 1;
// GET all products
app.MapGet("/api/products", () => Results.Ok(products));
// GET product by ID
app.MapGet("/api/products/{id:int}", (int id) =>
{
var product = products.FirstOrDefault(p => p.Id == id);
return product is null ? Results.NotFound() : Results.Ok(product);
});
// POST create product
app.MapPost("/api/products", (Product product) =>
{
var newProduct = product with { Id = nextId++ };
products.Add(newProduct);
return Results.Created($"/api/products/{newProduct.Id}", newProduct);
});
// PUT update product
app.MapPut("/api/products/{id:int}", (int id, Product updated) =>
{
var index = products.FindIndex(p => p.Id == id);
if (index == -1) return Results.NotFound();
products[index] = updated with { Id = id };
return Results.Ok(products[index]);
});
// DELETE product
app.MapDelete("/api/products/{id:int}", (int id) =>
{
var removed = products.RemoveAll(p => p.Id == id);
return removed > 0 ? Results.NoContent() : Results.NotFound();
});
app.Run();
4. Test with curl
# Create products
curl -X POST http://localhost:5000/api/products \
-H "Content-Type: application/json" \
-d '{"name":"Laptop","price":999.99}'
# Get all
curl http://localhost:5000/api/products
# Get by ID
curl http://localhost:5000/api/products/1
# Update
curl -X PUT http://localhost:5000/api/products/1 \
-H "Content-Type: application/json" \
-d '{"name":"Gaming Laptop","price":1299.99}'
# Delete
curl -X DELETE http://localhost:5000/api/products/1
Challenge
- Add input validation
- Implement search/filter by name
- Add pagination support
- Group endpoints using MapGroup
Expected Outcome
- Working CRUD API with Minimal APIs
- Proper HTTP status codes (200, 201, 204, 404)
- Clean, readable code