Minimal APIs in ASP.NET Core streamline the process of building HTTP APIs with reduced configuration and code, making them perfect for microservices and lightweight apps. They focus on providing only the essentials, significantly speeding up development while minimizing dependencies.
.NET Project CreationThe dotnet new web command creates a minimal API project in .NET that centers around a streamlined Program.cs file with simplified setup. We can run it in our current directory or specify a new folder with the -o option.
// Create in current directorydotnet new web// Create in new folderdotnet new web -o MyApiApp
In ASP.NET Core Minimal APIs, we use route parameters to capture dynamic values from URL paths. These parameters are defined with curly braces in the route pattern and automatically bind to handler method parameters. We can add type constraints to validate input format and ensure type safety.
// Basic route parameterapp.MapGet("/users/{id}", (int id) => $"User ID: {id}");// With type constraintapp.MapGet("/products/{id:int}", (int id) => $"Product ID: {id}");// String parameterapp.MapGet("/greet/{name}", (string name) => $"Hello, {name}!");
MapPostIn ASP.NET Core Minimal APIs, we use the MapPost() method to define HTTP POST endpoints that handle resource creation. These endpoints receive data in the request body and typically return a 201 Created response when successful. The method takes a route pattern and a handler function that processes the incoming data.
// POST endpoint that creates a productapp.MapPost("/api/products", (Product product) =>{// Add product to database or collectionproducts.Add(product);// Return 201 Created with location and the created resourcereturn Results.Created($"/api/products/{product.Id}", product);});
MapPostIn ASP.NET Core Minimal APIs, model binding automatically converts incoming JSON data to C# objects when we define a matching class and use it as a parameter in our endpoint handler.
// Class matching JSON structurepublic class Movie{public int Id { get; set; }public string Title { get; set; }public int Year { get; set; }}// POST endpoint with model bindingapp.MapPost("/api/movies", (Movie movie) =>{// JSON is already converted to Movie objectmovies.Add(movie);return Results.Created($"/api/movies/{movie.Id}", movie);});
In ASP.NET Core Minimal APIs, model binding automatically maps data from HTTP requests to method parameters based on parameter name and type. The framework intelligently selects the appropriate binding source without requiring explicit attributes in most cases, simplifying endpoint development.
// Route parameter bindingapp.MapGet("/api/products/{id}", (int id) =>{// id is automatically bound from the URL segmentreturn Results.Ok($"Product ID: {id}");});// Route parameter with multiple bindingsapp.MapGet("/api/orders/{orderId}/items/{itemId}", (int orderId, int itemId) =>{return Results.Ok($"Order {orderId}, Item {itemId}");});
MapPut()In ASP.NET Core Minimal APIs, we use the MapPut() method to define HTTP PUT endpoints that update existing resources. These endpoints typically use route parameters to identify the resource to update and receive the updated data in the request body. The method returns appropriate status codes based on whether the update succeeded.
// PUT endpoint for updating a productapp.MapPut("/api/products/{id}", (int id, Product updatedProduct) =>{var existingProduct = products.FirstOrDefault(p => p.Id == id);if (existingProduct == null)return Results.NotFound();// Update the existing productexistingProduct.Name = updatedProduct.Name;existingProduct.Price = updatedProduct.Price;return Results.Ok(existingProduct);});
MapDelete()In ASP.NET Core Minimal APIs, we use the MapDelete() method to define HTTP DELETE endpoints that remove resources from our application. These endpoints typically identify the resource to delete through route parameters and return appropriate status codes based on the operation outcome.
// DELETE endpoint to remove a resourceapp.MapDelete("/api/products/{id}", (int id) =>{var product = products.FirstOrDefault(p => p.Id == id);if (product == null)return Results.NotFound();products.Remove(product);return Results.NoContent();});
In ASP.NET Core Minimal APIs, we implement data validation by applying Data Annotations to model properties and manually validating objects in endpoint handlers. This approach lets us define rules directly on model classes and reject invalid data before processing it.
// Model with validation attributespublic class Product{[Required]public string Name { get; set; }[Range(0.01, 10000)]public decimal Price { get; set; }}// Endpoint with validationapp.MapPost("/api/products", (Product product) =>{var context = new ValidationContext(product);var results = new List<ValidationResult>();if (!Validator.TryValidateObject(product, context, results, true))return Results.BadRequest(results);// Process valid productreturn Results.Created($"/api/products/{product.Id}", product);});
In ASP.NET Core Minimal APIs, OpenAPI documentation is automatically generated when adding Swagger services. The framework creates API specifications that can be enhanced with metadata methods and viewed through Swagger UI.