Introduction to Minimal API

Related learning

  • Learn how to build fast, secure, and maintainable web apps with ASP.NET and the Razor Pages architecture.
    • With Certificate
    • Intermediate.
      17 hours
  • Jumpstart your career with this skill path, first by learning the C# language, then building web apps with ASP.NET Core and the Razor Pages.
    • Includes 7 Courses
    • With Certificate
    • Intermediate.
      41 hours

ASP.NET Minimal APIs

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 Creation

The 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 directory
dotnet new web
// Create in new folder
dotnet new web -o MyApiApp

ASP.NET Route Parameters

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 parameter
app.MapGet("/users/{id}", (int id) => $"User ID: {id}");
// With type constraint
app.MapGet("/products/{id:int}", (int id) => $"Product ID: {id}");
// String parameter
app.MapGet("/greet/{name}", (string name) => $"Hello, {name}!");

ASP.NET Core MapPost

In 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 product
app.MapPost("/api/products", (Product product) =>
{
// Add product to database or collection
products.Add(product);
// Return 201 Created with location and the created resource
return Results.Created($"/api/products/{product.Id}", product);
});

ASP.NET MapPost

In 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 structure
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public int Year { get; set; }
}
// POST endpoint with model binding
app.MapPost("/api/movies", (Movie movie) =>
{
// JSON is already converted to Movie object
movies.Add(movie);
return Results.Created($"/api/movies/{movie.Id}", movie);
});

ASP.NET Core Binding

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 binding
app.MapGet("/api/products/{id}", (int id) =>
{
// id is automatically bound from the URL segment
return Results.Ok($"Product ID: {id}");
});
// Route parameter with multiple bindings
app.MapGet("/api/orders/{orderId}/items/{itemId}", (int orderId, int itemId) =>
{
return Results.Ok($"Order {orderId}, Item {itemId}");
});

ASP.NET 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 product
app.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 product
existingProduct.Name = updatedProduct.Name;
existingProduct.Price = updatedProduct.Price;
return Results.Ok(existingProduct);
});

ASP.NET Core 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 resource
app.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();
});

ASP.NET Core Validation

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 attributes
public class Product
{
[Required]
public string Name { get; set; }
[Range(0.01, 10000)]
public decimal Price { get; set; }
}
// Endpoint with validation
app.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 product
return Results.Created($"/api/products/{product.Id}", product);
});

ASP.NET Core OpenAPI

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.

Learn more on Codecademy

  • Learn how to build fast, secure, and maintainable web apps with ASP.NET and the Razor Pages architecture.
    • With Certificate
    • Intermediate.
      17 hours
  • Jumpstart your career with this skill path, first by learning the C# language, then building web apps with ASP.NET Core and the Razor Pages.
    • Includes 7 Courses
    • With Certificate
    • Intermediate.
      41 hours